问题
Is there something like terminate or stop feature in pydub such that the stream after started by play() can be stopped abruptly while it is still playing instead of the audio being played to it's full length and then stopping.
回答1:
There is no direct way to stop an playing audio in pydub
at this time since it can either use pyaudio
or ffplay
in the backend (depending on what's installed and accessible).
See details on backend code here
However, you can hit Ctrl + c to break the play and wrap around play
method in try - except
block. It will generate KeyboardInterrupt
exception that you can process it according your needs.
Here is a working sample that's tested on windows
.
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_wav("audio.wav")
while True:
try:
play(song)
except KeyboardInterrupt:
print "Stopping playing"
break #to exit out of loop, back to main program
回答2:
At risk of being down voted for not referring to pydub, I thought I would share what I know at this point. I never got it to work with pydub and as far as I can tell, I used @Anil_M's answer. Let me share that again here as code formatting apparently does not work in comments.
from pydub import AudioSegment
from pydub.playback import play
# music files
f = '/home/worldwidewilly/workspace/deliberate-action/action/on-the-run-snippet.mp3'
# run pydub
sound = AudioSegment.from_file(f, format="mp3")
def ring():
sound_alarm = True
while True:
try:
print(f'sound_alarm is {sound_alarm}')
if sound_alarm == False:
return
play(sound)
except KeyboardInterrupt:
sound_alarm = False
print('done playing sound.')
break
if __name__ == "__main__":
import sys
ring()
When the above is executed and i press ctrl+C, the sound does stop playing, but it never gets to the KeyboardInterrupt logic, i.e. the print('done playing sound.')
is never executed. It just goes to the top of the loop, inrt the statement, and plays the sound (so, obviously, var sound_alarm never equals False).
The solution I have come upon is to use simpleaudio. The downside is that I have yet to figure out how to play anything other than a .wav file. Here is the code for that:
# run simpleaudio
wave_obj = sa.WaveObject.from_wave_file(f)
def ring():
# sound_alarm = True
while True:
try:
play_obj = wave_obj.play()
play_obj.wait_done()
except KeyboardInterrupt:
play_obj.stop()
print('done playing sound.')
break
if __name__ == "__main__":
import sys
ring()
Pressing ctrl-C here does stop the sound and it does end the loop. It is unclear why this logic would work for one and not the other, but there you have it. I would love to be enlightened.
来源:https://stackoverflow.com/questions/47596007/stop-the-audio-from-playing-in-pydub