Rudra Pratap Sinha
Rudra Pratap Sinha

Reputation: 169

Stop the audio from playing in pydub

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.

Upvotes: 5

Views: 8248

Answers (5)

Maximilian Wolf
Maximilian Wolf

Reputation: 83

As already mentioned pydub itself provides no such feature. However, it's possible to stop the music by using multiprocessing:

from pydub import AudioSegment
from pydub.playback import play
from multiprocessing import Process

some_audio = AudioSegment.from_file('yourAudioFile.mp3')
process = Process(target=play, args=(some_audio,))

if __name__ == '__main__':
    process.start()
    time.sleep(2000) # do some stuff inbetween
    process.terminate()

The method terminate()stops the process and with it the audio from playing.

EDIT

I found a much nicer way, sparing us unnecessarily heavy processes.

from pydub import AudioSegment
from pydub.playback import _play_with_simpleaudio

some_audio = AudioSegment.from_file('yourAudioFile.mp3')
playback = _play_with_simpleaudio(some_audio)
time.sleep(2000)  # do some stuff inbetween
playback.stop()  

More details: https://github.com/jiaaro/pydub/issues/160#issuecomment-497953546

Upvotes: 3

Neel Ranka
Neel Ranka

Reputation: 1

you can use Multithreading in the playback file of pydub to play/pause and even stop the music .

check the file here and replace the playback.py from pydub with this

https://github.com/NeelRanka/pydub_edited_play-pause-stop.git

Upvotes: 0

user3611941
user3611941

Reputation: 156

As far as I've seen, and I am using the whole sound processing for the first time, you could use pyaudio to play a wav-file as a stream. pyaudio is not pydub. :)

First, convert your anydata-file to a wav-file with pydub/ffmpeg, see below, and then use pyaudio to play it as a stream with logic between.

Because, when I play an MP3 with pydub, it waits some seconds and then states that the file has been converted to wav in a /tmp-folder. So, why not convert it just once and save it to your own location? It lasts some seconds both ways, anyway, but the latter converting has just to be done once (assuming you have tons of Gigabytes :) ), and then you can just check if the file already exists.

-> converting
Python convert mp3 to wav with Pydub

-> playing and recording sound with python -> pyaudio (comprehensive guide)
https://realpython.com/playing-and-recording-sound-python/#pyaudio

As you see in the code, you could put your own logic into the while loop where the stream is played.

I will try to use that combination in a project I make. Hope it works. :)

Upvotes: 1

Bill Turner
Bill Turner

Reputation: 879

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.

Upvotes: 0

Anil_M
Anil_M

Reputation: 11443

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

Upvotes: 0

Related Questions