wx.Sound 提供簡單的平台原生音效播放 (Windows 上呼叫 PlaySound API),支援 WAV 格式,適合簡單提示音、警報聲。
import wx
import wx.lib.filebrowsebutton as filebrowse
class SoundPlayerFrame(wx.Frame):
def __init__(self):
super().__init__(None, title="WAV 播放器", size=(600, 120))
self.SetBackgroundColour(wx.Colour(220, 240, 220))
panel = wx.Panel(self)
# 檔案瀏覽按鈕 (僅顯示 .wav)
self.fbb = filebrowse.FileBrowseButton(
panel, labelText="選擇 WAV 檔案:", fileMask="*.wav",
changeCallback=self.on_file_selected
)
self.play_btn = wx.Button(panel, label="▶ 播放")
self.play_btn.Bind(wx.EVT_BUTTON, self.on_play)
self.play_btn.Enable(False)
self.stop_btn = wx.Button(panel, label="■ 停止")
self.stop_btn.Bind(wx.EVT_BUTTON, self.on_stop)
self.stop_btn.Enable(False)
# 版面配置
hbox = wx.BoxSizer(wx.HORIZONTAL)
hbox.Add(self.fbb, 1, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 10)
hbox.Add(self.play_btn, 0, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 5)
hbox.Add(self.stop_btn, 0, wx.ALIGN_CENTER_VERTICAL)
vbox = wx.BoxSizer(wx.VERTICAL)
vbox.Add(hbox, 0, wx.EXPAND | wx.ALL, 15)
panel.SetSizer(vbox)
self.sound = None
self.current_file = None
def on_file_selected(self, event):
self.current_file = self.fbb.GetValue()
self.play_btn.Enable(bool(self.current_file))
def on_play(self, event):
if not self.current_file:
return
try:
self.sound = wx.Sound(self.current_file)
if self.sound.IsOk():
self.sound.Play(wx.SOUND_ASYNC) # 非同步播放
self.play_btn.Enable(False)
self.stop_btn.Enable(True)
else:
wx.MessageBox("無效的 WAV 檔案", "錯誤", wx.ICON_ERROR)
except Exception as e:
wx.MessageBox(f"播放失敗: {e}", "錯誤", wx.ICON_ERROR)
def on_stop(self, event):
if self.sound:
self.sound.Stop()
self.play_btn.Enable(True)
self.stop_btn.Enable(False)
if __name__ == '__main__':
app = wx.App(False)
frame = SoundPlayerFrame()
frame.Show()
app.MainLoop()
wx.Sound(filename):載入 WAV 檔案,失敗時 IsOk() 回傳 False。Play(flags):
wx.SOUND_ASYNC:非同步 (預設),立即返回。wx.SOUND_SYNC:同步阻塞直到播放完畢。wx.SOUND_LOOP:循環播放 (需搭配 ASYNC)。Stop():停止播放。IsPlaying():檢查是否正在播放。wx.lib.filebrowsebutton.FileBrowseButton 整合了文字框與檔案對話框,fileMask 過濾副檔名,changeCallback 即時響應選擇。
python-vlc、pygame.mixer 或 gstreamer。