Search code examples
python-3.xaudio

How to play sound with python and no while loop


I want to play sound through my python script:

I have used win_sound pyglet playsound and pygame but it doesn't want to work.

Is there any way to do this.

the directory is C:Users/Random/Folder/OtherFolder/Sound1


Solution

  • You can use librosa for loading audio data and sounddevice for playing audio.

    Like this:

    import time
    import librosa
    import sounddevice as sd
    
    
    def play_audio(audio_path, sampling_rate=44100):
    
        audio, sampling_rate = librosa.load(audio_path, sr=sampling_rate)
        
        duration = librosa.core.get_duration(audio, sr=sampling_rate)
        
        # play the audio
        sd.play(audio, sampling_rate)
        # wait until the audio is done playing
        time.sleep(duration)
    
    
    
    play_audio('./test.mp3')
    

    Moreover, if this function causes the rest of your program to freeze ( because of time.sleep ) you need to run the play_audio function on a separate thread like here.