user3423572
user3423572

Reputation: 559

Playing mp3 files using python 2.7 buttons - TKinter

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

Answers (2)

ahaltindis
ahaltindis

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

TidB
TidB

Reputation: 1759

You have two mistakes there:

  1. 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(...))
    
  2. winsound is not made to play mp3s, but wavs. Use another library, suggestions can be found here.

Upvotes: 0

Related Questions