【问题标题】:Stop Winsound / Stop a thread on Python停止 Winsound / 停止 Python 上的线程
【发布时间】:2014-05-29 09:23:55
【问题描述】:

我正在使用 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

【问题讨论】:

    标签: python multithreading audio tkinter


    【解决方案1】:

    您的代码中有两个主要问题:

    1. 全局变量 flag_play 必须放置在声音播放循环中,在您的情况下是在 PlayThis() 函数中
    2. 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()
    

    如果您需要更多支持,请告诉我。

    【讨论】:

    • @shaktimaan,看起来更好,感谢编辑。希望它也能帮助我获得一些声望点。
    【解决方案2】:

    我还在 Adob​​e Audition 中创建了一个包含静音的 0.5 秒 wav 文件并将其附加到停止按钮,这基本上“停止”了之前播放的音频剪辑的播放。

    【讨论】:

      【解决方案3】:

      我找到了一种方法,通过向按钮添加 0.5 秒的声音,这样当我按下按钮时,它会停止背景播放按钮一,然后停止程序中的所有声音。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多