Play Audio with Python

Play audio with Python

You can find information about Python audio here: http://wiki.python.org/moin/Audio/

It doesn't look like it can play .mp3 files without external libraries. You could either convert your .mp3 file to a .wav or other format, or use a library like PyMedia.

Playing mp3 song on python

Try this. It's simplistic, but probably not the best method.

from pygame import mixer  # Load the popular external library

mixer.init()
mixer.music.load('e:/LOCAL/Betrayer/Metalik Klinik1-Anak Sekolah.mp3')
mixer.music.play()

Please note that pygame's support for MP3 is limited. Also, as pointed out by Samy Bencherif, there won't be any silly pygame window popup when you run the above code.

Installation is simple -

$pip install pygame

Update:

Above code will only play the music if ran interactively, since the play() call will execute instantaneously and the script will exit. To avoid this, you could instead use the following to wait for the music to finish playing and then exit the program, when running the code as a script.

import time
from pygame import mixer

mixer.init()
mixer.music.load("/file/path/mymusic.ogg")
mixer.music.play()
while mixer.music.get_busy(): # wait for music to finish playing
time.sleep(1)

Play a sound asynchronously in a while loop

I managed to solve this the next day.

I used threading and i had to use it in a class to check if it's alive because I couldn't just t1 = threading.Thread(target=func) t1.start() in the while loop because i needed to check if the thread is alive before.

So...

import threading

from playsound import playsound

class MyClass(object):
def __init__(self):
self.t1 = threading.Thread(target=play_my_sound)

def play_my_sound():
playsound('sound.wav')

def loop():
while True:
if not my_class.t1.is_alive():
my_class.t1 = threading.Thread(target=play_my_sound)
my_class.t1.start()

if __name__ == "__main__":
my_class = MyClass()
loop()

This answers my question, the sound plays on it's own thread in the while loop and it only starts playing if the previous one has finished.

Note: i had issues with the playsound library, but it was because i had to use \\ for the path instead of / - in my original code the sounds are not in the same folder as the main script. I also had to downgrade to playsound==1.2.2 version.



Related Topics



Leave a reply



Submit