如何使用 playsound 模块停止音频?

How to stop audio with playsound module?

如何在 Python 代码中停止通过 playaudio 模块播放音频? 我播放过音乐,但我无法停止那音乐。我该如何阻止它?

playsound.playsound("name_of_file")

Playsound是一个单一的功能模块,就是播放声音,除此之外别无其他。这似乎意味着它也不会停止播放声音。来自他们自己的文档:

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

就我个人而言,我喜欢使用 pyaudio. The following code is adapted from the example here。该代码播放音频并将 space 栏设置为 pause/play 按钮。

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

在 windows 上尝试: import winsound

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

停止播放:

winsound.PlaySound(None, winsound.SND_PURGE)

您可以使用多处理模块作为后台进程播放声音,然后随时终止它:

import multiprocessing
from playsound import playsound

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

这里有一个更简单的方法:

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

您可以从另一个线程更改 globals()["allowSound"] 并在音频结束时将其设置为 false(您可以使用 wmp.durationString 获取音频的长度)

这里有一些关于此的更多信息:Windows Media Player COM Automation works from VBS but not from Python

虽然这不使用 playsound 模块,但它是一个不错的选择。

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

程序成功执行后,音频文件将开始播放。现在点击终端,一旦你看到光标,输入 Ctrl+C,它将带你离开终端,音频也将停止播放。

使用的编程指令:

from playsound import playsound

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