Reputation: 11
I'm making a game where you're a space shuttle evading oncoming meteors, this is my first Python program and I really struggle with the music part: the idea is to only use wxPython
(pyGame
is forbidden).
Currently I somehow managed to get the music to play when you click on a button, but then I can't control the space ship anymore.
I don't fully understand what's going on, I've been searching for days with no answers.
class Board(wx.Panel):
BoardWidth = 5
BoardHeight = 12
Speed = 50
ID_TIMER = 1
def __init__(self,parent):
wx.Panel.__init__(self,parent)
self.timer = wx.Timer(self, Board.ID_TIMER)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
self.Bind(wx.EVT_TIMER, self.OnTimer, id=Board.ID_TIMER)
self.ClearBoard()
self.music = wx.Panel(self)
button = wx.Button(self, label="Play")
self.music=wx.media.MediaCtrl(self.music, -1, "game.mp3")
button.Bind(wx.EVT_BUTTON, self.play)
def play(self,event):
self.music.Play()
As far as I'm concerned this how I imagine it should work, but it doesn't:
#...
self.music=wx.media.MediaCtrl(self, -1, "game.mp3")
self.Bind(wx.media.EVT_MEDIA_LOADED, self.play)
def play(self,event):
self.music.Play()
Upvotes: 0
Views: 2678
Reputation: 2664
You can use a thread to play the music. Right now your frame freezes while it waits for the music to finish, which of course never happens, as it is background music.
There is a strange bug where the event is never generated. To solve this, add szBackend=wx.media.MEDIABACKEND_WMP10
(see code below)
try:
import threading
#...
self.music=wx.media.MediaCtrl(self.music, -1, "game.mp3",
szBackend=wx.media.MEDIABACKEND_WMP10)
#...
def play(self, event):
threading.Thread(target=self.music.Play).start()
Alternatively, you could use a timer to wait for the file to be loaded:
def __init__(self, parent):
#...
self.play()
def play(self):
threading.Timer(0.5, self.music.Play).start()
Upvotes: 2