I want to play a music file with mpg321
using Python using another event as the trigger. Then, when I type in a specific string, I'd like the music to stop playing.
How can I do this using Python?
import os
from subprocess import Popen, PIPE
music = None
while 1:
cmd = raw_input('> ')
if cmd.lower() == 'play':
music = Popen('mpg321 /home/Torxed/test.mp3'.split(' ',1), stdout=PIPE, stderr=STDOUT, close_fds=True)
elif cmd.lower() == 'stop':
try:
music.stdout.close()
music.stdin.close()
except:
pass
music = None
Instead of using subprocess you could do:
music = os.popen('mpg321 /home/Torxed/test.mp3', 'w')
and just do
music.close()
I still think this is a horrible solution, because you shouldn't rely on out-side sources to do your task if you're a programmer.. it should be handled within your application and not so much on the os or some 3:d party application.
Pygame: Go with for instance Pygame, it will do the job for you and then some.
import pygame, time
pygame.init()
pygame.mixer.music.load('/home/Torxed/test.mp3')
pygame.mixer.music.play()
time.sleep(5)
pygame.mixer.music.fadeout(5)
The Snack Sound Toolkit: It's a pure Python audio library with great flexibility!
s = Sound()
s.read('/home/Torxed/test.mp3')
s.play()
Pyglet: Easily my favorite, a cross-platform graphic OpenGL library with access to music as well:
import pyglet
music = pyglet.resource.media('/home/Torxed/test.mp3')
music.play()
pyglet.app.run()
Winsound Is a Windows only alternative
import winsound
winsound.PlaySound('C:\\users\\Torxed\\Desktop\\test.mp3')
OSSaudio This is a native Linux alternative to the others, OSS is one of the most default audio playbacks on Linux/Unix systems so it shouldn't be a strange option for most of the people out there. (Courtesy of @orestis here on Stackoverflow)
from wave import open as waveOpen
from ossaudiodev import open as ossOpen
s = waveOpen('/home/Torxed/test.wav','rb')
(nc,sw,fr,nf,comptype, compname) = s.getparams( )
dsp = ossOpen('/dev/dsp','w')
try:
from ossaudiodev import AFMT_S16_NE
except ImportError:
if byteorder == "little":
AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
else:
AFMT_S16_NE = ossaudiodev.AFMT_S16_BE
dsp.setparameters(AFMT_S16_NE, nc, fr)
data = s.readframes(nf)
s.close()
dsp.write(data)
dsp.close()
Some googling which led me to the OSS solution gave me this (be sure to credit those guys, good examples): Play a Sound with Python
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With