What's a cross platform way to play a sound file in python?

前端 未结 5 865
庸人自扰
庸人自扰 2020-12-28 16:56

I tried playing a .wav file using pyaudio. It works great on windows, but doesn\'t work in Ubuntu when another device is using sound.

The error is \"I

相关标签:
5条回答
  • 2020-12-28 17:25

    Have you looked at pymedia? It looks as easy as this to play a WAV file:

    import time, wave, pymedia.audio.sound as sound
    f= wave.open('YOUR FILE NAME', 'rb')
    sampleRate= f.getframerate()
    channels= f.getnchannels()
    format= sound.AFMT_S16_LE
    snd= sound.Output(sampleRate, channels, format)
    s= f.readframes(300000)
    snd.play(s)
    while snd.isPlaying(): time.sleep(0.05)
    

    Ref: http://pymedia.org/tut/play_wav.html

    Of course, you can have a look at the Python wiki under Audio (http://wiki.python.org/moin/Audio/) for other libraries such as https://docs.python.org/library/wave.html or again in Python's wiki under Game Libraries (http://wiki.python.org/moin/PythonGameLibraries) that will point you to bindings to OpenAL or Pygame that has sound modules.

    And finally, although I don't know the limitations of pyaudio, your error message sounds more like the library is not able to find the default output device more than the device is in use by another process. Maybe have a look at what output device is returned by the get_default_output_device_info of pyaudio and compare it to whatever's your default setting in Ubuntu.

    0 讨论(0)
  • 2020-12-28 17:26

    You can try Simpleaudio:

    > pip install simpleaudio
    

    Then:

    import simpleaudio as sa
    
    wave_obj = sa.WaveObject.from_wave_file("path/to/file.wav")
    play_obj = wave_obj.play()
    play_obj.wait_done()
    
    0 讨论(0)
  • 2020-12-28 17:28

    You can use wxPython

    sound = wx.Sound('sound.wav')
    sound.Play(wx.SOUND_SYNC)
    

    or

    sound.Play(wx.SOUND_ASYNC)
    

    Here is an example from the wxPython demo.

    0 讨论(0)
  • 2020-12-28 17:31

    I found playsound to be the simplest.

    from playsound import playsound
    
    is_synchronus = False
    playsound(r"C:\Windows\Media\chimes.wav", is_synchronus)
    
    0 讨论(0)
  • 2020-12-28 17:33

    I'm not absolutely sure if that fulfills your requirements, but I immediately thought PyGame

    http://www.pygame.org/docs/ref/mixer.html#pygame.mixer.Sound

    from pygame import mixer
    
    mixer.init()
    s = mixer.Sound('sound.wav')
    s.play()
    
    0 讨论(0)
提交回复
热议问题