How to stop audio with playsound module?

How do I stop the audio playing through playaudio module in Python code?
I have played music but I can’t stop that music. How can I stop it?

playsound.playsound("name_of_file")

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use the multiprocessing module to play the sound as a background process, then terminate it anytime you want:

import multiprocessing
from playsound import playsound

p = multiprocessing.Process(target=playsound, args=("file.mp3",))
p.start()
input("press ENTER to stop playback")
p.terminate()

Method 2

Playsound is a single function module that plays sounds, and nothing else. It would seem that means it does not stop playing sounds either. From their own documentation:

The playsound module contains only one thing – the function (also named) playsound.

Personally, I like to use pyaudio. The following code is adapted from the example here. The code plays audio and has the space bar set as a pause/play button.

import pyaudio
import wave
import time
from pynput import keyboard

paused = False    # global to track if the audio is paused
def on_press(key):
    global paused
    print (key)
    if key == keyboard.Key.space:
        if stream.is_stopped():     # time to play audio
            print ('play pressed')
            stream.start_stream()
            paused = False
            return False
        elif stream.is_active():   # time to pause audio
            print ('pause pressed')
            stream.stop_stream()
            paused = True
            return False
    return False


# you audio here
wf = wave.open('audio\songs\And_Your_Bird_Can_Sing_mp3_2_wav.wav', 'rb')

# instantiate PyAudio
p = pyaudio.PyAudio()

# define callback
def callback(in_data, frame_count, time_info, status):
    data = wf.readframes(frame_count)
    return (data, pyaudio.paContinue)

# open stream using callback
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=wf.getframerate(),
                output=True,
                stream_callback=callback)

# start the stream
stream.start_stream()

while stream.is_active() or paused==True:
    with keyboard.Listener(on_press=on_press) as listener:
        listener.join()
    time.sleep(0.1)

# stop stream
stream.stop_stream()
stream.close()
wf.close()

# close PyAudio
p.terminate()

Method 3

On windows try:
import winsound

winsound.PlaySound(r'C:sound.wav', winsound.SND_ASYNC)

Stop Playback:

winsound.PlaySound(None, winsound.SND_PURGE)

Method 4

#pip install pygame
from pygame import mixer
import time
mixer.init() #Initialzing pyamge mixer

mixer.music.load('lovingly-618.mp3') #Loading Music File

mixer.music.play() #Playing Music with Pygame

time.sleep(5)


mixer.music.stop()

Method 5

Here is a much easier way:

wmp = win32com.client.dynamic.Dispatch("WMPlayer.OCX")
wmp.settings.autoStart = True
wmp.settings.volume = 100
wmp.URL = file
while globals()["allowSound"]:
    PumpWaitingMessages()

You can change globals()[“allowSound”] from another thread and set it to false when the audio has ended (you can get the length of the audio with wmp.durationString)

Here is some more info about this: Windows Media Player COM Automation works from VBS but not from Python

Although this does not use the playsound module it is a good alternative.

Method 6

After successful execution of the program, audio file will start playing. Now Click on terminal, once you see the cursor, type Ctrl+C, it will bring you out of the terminal and audio will also stop playing.

Programming Instructions used:

from playsound import playsound

playsound('//path//to//a//sound//file//you//want//to//play.mp3')

Method 7

EASY……
on your terminal tab, look for kill(delete) option on the right hand side.
click the delete option and it will stop playing


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x