【问题标题】:how to play audio file in python?如何在python中播放音频文件?
【发布时间】:2013-05-16 17:24:54
【问题描述】:

我刚开始使用带有 GUI 界面的 python。我一直在一个简单的计时器程序上试验 TKinter。我被卡住了,因为我想用警报播放一首歌,但找不到解决方案。我正在研究 Linux mint。我有一个消息窗口,时间到了就会出现,我想随着窗口一起启动音频,当你退出窗口时,音频停止。我的代码如下所示。

from Tkinter import *
import tkMessageBox


def messageWindow():
    win = Toplevel()
    b = Button(win, text='Times Up!',
        bg="yellow", fg="green",
        activebackground="purple", activeforeground="white",
        command=quit)
    b.pack(ipadx=root.winfo_screenwidth()/2,
        ipady=root.winfo_screenheight()/2)

    root.mainloop()

def alert():
    #this is were i would a call the function to play mp3
    messageWindow()
    quit()

def start():
    root.after(scale.get() * 1000, alert)

root = Tk()

minutes = Label(root, text ="Minutes:  ")
minutes.grid(row=0, column=0)

scale = Scale(root, from_=1, to=60, orient=HORIZONTAL, length=450)
scale.grid(row=0, column=1) 

button = Button(root,text= "Start Timing", command=start)
button.grid(row=1, column=1, pady=5, sticky=E)

root.mainloop()

【问题讨论】:

标签: python audio timer tkinter


【解决方案1】:

pygame 包含执行此操作的功能。我不知道这是否是最好的方式,但它肯定是一种方式。

import pygame

pygame.init()
pygame.mixer.init()
sounda= pygame.mixer.Sound("desert_rustle.wav")

sounda.play()
sounda.stop()

示例取自here

【讨论】:

    【解决方案2】:

    似乎您已经对答案感到满意(诚然,您在 3 年前接受了这个答案!),但您可以为未来的项目考虑以下替代方案: 使用import winsound。 Pygame 对我不起作用(可能是因为我使用的是 python 3),但更重要的是,winsound 一开始可能会让音频更容易播放,据我所知,它对你的目的很有效.您需要使用“.wav”文件(与 mp3 之类的文件相反),但如果您查找 'online converter',则可以轻松转换为该格式。

    import winsound
    
    winsound.PlaySound('The Countdown.wav', winsound.SND_ASYNC)
    

    以防万一您确实需要提前停止音频,您不能使用 stop()。相反,使用

    winsound.PlaySound(None, 0)
    

    也许 pyglet 无论如何都会这样做,但 winsound.SYND_ASYNC 的优点在于它将与 tkinter 一起运行,而不是暂停程序/等到程序完成后再执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-26
      • 2021-02-07
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-02
      • 2011-11-09
      • 2013-06-17
      相关资源
      最近更新 更多