Search code examples
pythonmultithreadingaudiopyglet

Pyglet: 'str' object has no attribute 'audio_format' (python)


Im attempting to play an Mp3 file in pyglet from a file chosen through open file dialogue, but even though the file ends with a .mp3 extension, i still receive the error:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python34\lib\threading.py", line 921, in _bootstrap_inner
    self.run()
  File "C:\Python34\lib\threading.py", line 869, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Python34\MP2.py", line 44, in real_playMusic
    player.queue(f)
  File "C:\Python34\lib\site-packages\pyglet-1.2.3a1-py3.4.egg\pyglet\media\__init__.py", line 977, in queue
    group = SourceGroup(source.audio_format, source.video_format)
AttributeError: 'str' object has no attribute 'audio_format'

I was wondering how to overcome this error and be able to have the file read and played back?

Code:

from tkinter import *
from tkinter.filedialog import askopenfilename
import pyglet
import pyglet.media as media
from threading import Thread

app = Tk()
app.title("Music Player")
app.geometry("600x200")
have_avbin = True 

f='' #intialize variable

def openFile():
    global f
    f =  filedialog.askopenfilename(filetypes = (("Mp3 files", "*.mp3"),("Wav files", "*.wav"),("All files","*.*")))




#Creates menu bar for opening MP3s, and closing the program
menu = Menu(app)
file = Menu(menu)
file.add_command(label='Open', command=  openFile) # replace 'print' with the name of your open function
file.add_command(label='Exit', command=app.destroy) # closes the tkinter window, ending the app
menu.add_cascade(label='File', menu=file)
app.config(menu=menu)

#Run each app library mainloop in different python thread to prevent freezing
def playMusic():
    global player_thread
    player_thread = Thread(target=real_playMusic)
    player_thread.start()

def stopMusic():
    global player_thread
    player_thread = Thread(target=real_stopMusic)
    player_thread.start()

#Play open file function attached to button
def real_playMusic():
    src=pyglet.media.load(f, streaming=False)
    player = pyglet.media.Player();
    player.queue(f)
    player.play()
    pyglet.app.run()

#Stop the music function
def real_stopMusic():
     pyglet.app.event_loop.stop()




#Play button creation
btnPlay = Button(app, text ="Play", command = playMusic)
btnPlay.grid(row =10, column = 0)


#Pause button creation
btnPause = Button(app)
btnPause.grid()
btnPause.configure(text = "Stop", command = stopMusic)



app.mainloop() # keep at the end

Solution

  • This should work:

    player.queue(src)