Reputation: 559
Hello I am trying to create a button that plays a mp3 file using TKinter so far I have the following code. I cant get it to play the mp3 file
from Tkinter import *
import os
import winsound
app = Frame(root)
app.pack(side='bottom')
button1 = Button(app, text="Enter Program", command=winsound.PlaySound('music.mp3',winsound.SND_FILENAME))
button1.pack()
Thanks
Upvotes: 1
Views: 3194
Reputation: 373
You can use pyglet library to play mp3 files but you should also have installed avbin
library. (https://code.google.com/p/avbin/)
Another problem is, tkinter has its own main loop and pyglet has its own. So you should use threads. This code might give you an idea:
from Tkinter import *
from threading import Thread
import pyglet
root = Tk()
app = Frame(root)
app.pack(side='bottom')
player = pyglet.media.Player()
music_file = pyglet.media.load('foo.mp3')
def startPlaying():
player.queue(music_file)
player.play()
pyglet.app.run()
def playSound():
global sound_thread
sound_thread = Thread(target=startPlaying)
sound_thread.start()
button1 = Button(app, text="Enter Program", command=playSound)
button1.pack()
root.mainloop()
pyglet.app.exit()
Upvotes: 3
Reputation: 1759
You have two mistakes there:
The classic command
error: When you pass an argument like this:
Button(..., command=winsound.PlaySound(...))
you're calling PlaySound
and use its return value (which defaults to None
), so you're passing command=None
. Use lambda
:
Button(..., command=lambda: winsound.PlaySound(...))
winsound
is not made to play mp3
s, but wav
s. Use another library, suggestions can be found here.
Upvotes: 0