我正在使用 Tkinter 在 python 上写一个小游戏(顺便说一下,我不允许使用任何其他非内置模块)并且我想在主窗口上播放背景歌曲,这是那个包含标题,以及转到其他窗口和内容的按钮...
所以问题是当我进入另一个窗口时我需要停止声音,但是当我按下按钮去另一个窗口时,歌曲继续播放...
我正在使用 winsound 模块,并定义了几个函数,(顺便说一下,它们非常糟糕)在我第一次使用线程运行程序时播放这首歌...
所以这是交易,我想在函数“killsound”中添加一些东西,这样我就可以将它添加到每个按钮,然后当我按下任何按钮打开任何其他窗口时,声音就会被杀死。
我希望有类似“a.kill()”或“a.stop()”的东西,但它没有用。
而且我真的不知道如何在 winsound 上使用 SND_PURGE 东西......虽然我知道 SND_PURGE 不再适用于新的 Windows 操作系统(获得 Win8.1)
你能帮帮我吗?
谢谢! (对不起,令人毛骨悚然的英语...)
def Play(nombre): #This function Is the core of the winsound function
ruta = os.path.join('Audio',nombre)
Reproducir= winsound.PlaySound(ruta,winsound.SND_FILENAME)
return Reproducir
def PlayThis():
while flag_play:
try:
return Play('prettiest weed.wav')
except:
return "Error"
def PlayThisThread():
global flag_play
flag_play= True
a=Thread(target=PlayThis, args=())
a.daemon = True
a.start()
PlayThisThread()
def killsound(): #This is the function I want, for killing sound.
global flag_play
flag_play = False
请您参考如下方法:
您的代码中存在两个主要问题:
- 全局变量
flag_play必须放在声音播放循环中,在您的例子中是在PlayThis()函数中 Winsound模块的目标是简单的非线程使用。播放声音时,没有机会“轻声”打断。它不支持任何播放状态报告,例如.isPlaying()或您需要的任何类型的.stop()来终止它。
解决方法:
尝试 PyMedia包裹。 Pymedia 允许较低级别的音频操作,因此必须在初始化时提供更多详细信息:
import time, wave, pymedia.audio.sound as sound # little to do on the proper audio setup f= wave.open( 'prettiest weed.wav', 'rb' ) sampleRate= f.getframerate() # reads framerate from the file channels= f.getnchannels() format= sound.AFMT_S16_LE # this sets the audio format to most common WAV with 16-bit codec PCM Linear Little Endian, use either pymedia or any external utils such as FFMPEG to check / corvert audio into a proper format. audioBuffer = 300000 # you are able to control how much audio data is read
通过以下分配,“snd”成为类 sound.Output 的一个实例并给你一堆有用的音频方法:
snd= sound.Output( sampleRate, channels, format )
s= f.readframes( audioBuffer )
snd.play( s )
最后,您的线程播放循环可能如下所示:
while snd.isPlaying():
global flag_play
if not flag_play: snd.stop() #here is where the playback gets interupted.
time.sleep( 0.05 )
f.close()
如果您需要更多支持,请告诉我。
