我正在基于Pyo和WX库在Python中构建一个简单的信号发生器。
我已经完成了每个教程的简单教程,并成功地将WX中的按钮绑定到WX函数。我现在试图按下标有“振荡器1”的按钮,产生一个简单的正弦波(440赫兹)1秒;但是,当main()函数执行时,正在播放正弦音,当按钮显示在wx帧中时,我无法重新触发正弦音。这两种症状都是不受欢迎的。
为什么程序执行时会立即播放正弦音?为什么firstOSC按钮看起来不起作用?
import wx
from pyo import *
import time
pyoServer = Server().boot()
pyoServer.start()
class MainWindow(wx.Frame):
def __init__(self,parent,title):
wx.Frame.__init__(self,parent,title=title, size = (640,640))
self.CreateStatusBar() # A StatusBar in the bottom of the window
# Signal Generator controls
oscillator = SoundOutput()
firstOSC = wx.Button(self, wx.ID_YES,"Oscillator 1 " + str(oscillator.str_osc1State))
self.Bind(wx.EVT_BUTTON, oscillator.OnOff1(440), firstOSC)
#Menus
filemenu = wx.Menu()
menuExit = filemenu.Append(wx.ID_EXIT,"&Exit","Terminate the program")
menuBar = wx.MenuBar()
menuBar.Append(filemenu,"&File")
self.SetMenuBar(menuBar)
self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
self.Show(True)
def OnExit(self,e):
self.Close(True)
class SoundOutput(object):
def __init__(self):
self.osc1State = False
self.str_osc1State = "Off"
self.a = Sine(440, 0, 0.1)
def OnOff1(self, frequency):
self.a.freq = frequency
self.a.out()
time.sleep(1)
self.osc1State = True
def Main():
app = wx.App(False)
frame = MainWindow(None,"Signal Generator")
app.MainLoop()
答案 0 :(得分:1)
我通过调查WX如何处理事件来解决这个问题。事实证明,由于某种原因,在类的嵌套或单独实例中调用方法会导致在运行时而不是在事件上播放音调。我通过为MainWindow类创建一个方法来解决这个问题,该方法充当firstOSC的绑定事件处理程序。然后,此方法调用实际振荡器类的必要方法。
这是新代码:
# Signal Generator controls
self.fOscillator = SoundOutput()
self.fOscillatorstatus = False
self.firstOSC = wx.Button(self, wx.ID_ANY,"Oscillator 1 On")
self.firstOSC.Bind(wx.EVT_BUTTON, self.OnFirstOSC)
def OnFirstOSC(self,e):
if not self.fOscillatorstatus:
self.fOscillator.OnOff1(440)
self.fOscillatorstatus = True
self.firstOSC.SetLabel("Oscillator 1 Off")
elif self.fOscillatorstatus:
self.fOscillator.OnOff1(0)
self.firstOSC.SetLabel("Oscillator 1 On")
self.fOscillatorstatus = False