简体   繁体   中英

how to play audio file in python?

I am just starting using python with a GUI interface. I've been experimenting with TKinter on a simple timer program. I am stuck, because I want to have a song play with the alert,but have not been able to find a solution. I am working on Linux mint. I have a message window that appears when the time is up, and i would like to start the audio along with the window, and when you exit the window, the audio stops. my code looks like this.

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

pygame includes the functionality to do this. I don't know if it is the best way but it is certainly a way.

import pygame

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

sounda.play()
sounda.stop()

example taken from here

Seems like you're already happy with an answer (which you accepted 3 years ago, admittedly!) but here's an alternative you could consider for future projects: use import winsound . Pygame didn't work for me (possibly down to the fact that I'm using python 3), but more importantly, winsound probably makes audio simpler to play in the first place and it would be effective for your purposes as far as I know. You need to use a '.wav' file (as opposed to something like mp3), but it's easy to convert to that format if you look up 'online converter' .

import winsound

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

Just in case you do need to stop the audio early, you can't use stop(). Instead, use

winsound.PlaySound(None, 0)

Perhaps pyglet does this anyway, but what's great about winsound.SYND_ASYNC is that it will run in conjunction with tkinter instead of halting the program/ waiting until the program finishes, to execute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM