12

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")
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Kashish Jain
  • 133
  • 1
  • 2
  • 7
  • You will need to show us some more code. This is very little to work with. – harmonica141 Jul 23 '19 at 07:27
  • like i have one file named drinking_water.mp3 then i want to stop the music when i inputs stop then i am not able to stop the music . i enter the code playsound.playsound("drinking_water.mp3") but i want to stop the music in middle, then what should be the code for stopping that playing music – Kashish Jain Jul 23 '19 at 15:56

7 Answers7

17

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()
Artemis
  • 2,553
  • 7
  • 21
  • 36
Aakash Singh
  • 409
  • 5
  • 13
8

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()
4

On windows try: import winsound

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

Stop Playback:

winsound.PlaySound(None, winsound.SND_PURGE)
Ben Rauzi
  • 564
  • 4
  • 13
3
#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()
am96en
  • 59
  • 2
  • 2
    Code only answers are discouraged. Please provide a summary of how your answer solves the problem and why it may be preferable to the other answers provided. – DaveL17 Apr 20 '21 at 22:53
0

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.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Wudfulstan
  • 129
  • 11
-1

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')
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • 9
    That will stop the whole program, which may or may not be what the OP wants. The accepted answer seems to be a better solution. – Robert Jun 15 '21 at 15:09
-1

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

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61