0

我正在制作一个游戏,你是一个逃避迎面而来的流星的航天飞机,这是我的第一个 Python 程序,我真的在音乐部分苦苦挣扎:这个想法是只使用wxPython(pyGame是被禁止的)。

目前,当您单击一个按钮时,我以某种方式设法让音乐播放,但后来我无法再控制宇宙飞船了。

我不完全明白发生了什么,我一直在寻找几天没有答案。

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

就我而言,我认为它应该如何工作,但它没有:

    #...
    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()
4

1 回答 1

2

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()
于 2012-05-26T13:51:19.050 回答