0

我在 python2-7 我想在 tkinter 中获得一个按钮,它停止阅读用流体合成器创建的笔记。

我发现常见的解决方案是使用 time.after 像这里:你如何创建 Tkinter GUI 停止按钮来打破无限循环?

但在我的情况下,我不能使用它,因为我需要在 noteon 和 noteoff 之间有一段时间来为我的笔记提供持续时间。此外,我只想在单击开始时播放音符(而不是像链接中的解决方案一样在开头)。

所以我创建了这段代码,但它不起作用,因为 var_start 总是初始化为 int:

from tkinter import*
import fluidsynth
import time

fs=fluidsynth.Synth()
fs.start(driver='alsa', midi_driver='alsa_seq')
org_charge = fs.sfload("organ.sf2")
fs.program_select(0,org_charge, 0, 0)
time.sleep(1)

var_start=int

def start():
    global var_start
    var_start=1

def stop():
    global var_start
    var_start=0

root=Tk()

if var_start==1:
    fs.noteon(0,67,127)
    time.sleep(1)
    fs.noteoff(0,67)
    fs.noteon(0,71,127)
    time.sleep(1)
    fs.noteoff(0,71)
    fs.noteon(0,74,127)
    time.sleep(1)
    fs.noteoff(0,74)

Button(root, text='start', command= start).pack(padx=10, pady=10)    
Button(root, text='stop', command= stop).pack(padx=10, pady=10)    

root.mainloop()

我没有其他想法来重塑我的代码......有人可以帮助我吗?

谢谢

4

1 回答 1

0

您启动var_startintin 语句,因此永远不会执行var_start=int代码块。if var_start==1:而您的start()功能只是将 更改var_start为 1 并且永远不会开始播放音符,因此不会发生任何事情。

永远不要调用time.sleep()主线程,因为它会阻塞tkinter主循环。您可以.after(...)用来模拟播放循环,下面是一个示例代码块:

playing = False

def play_notes(notes, index, noteoff):
    global playing
    if noteoff:
        fs.noteoff(0, notes[index])
        index += 1      # next note
    if playing and index < len(notes):
        fs.noteon(0, notes[index], 127)
        # call noteoff one second later
        root.after(1000, play_notes, notes, index, True)
    else:
        # either stopped or no more note to play
        playing = False
        print('done playing')

def start_playing():
    global playing
    if not playing:
        print('start playing')
        playing = True
        notes = [67, 71, 74, 88, 80, 91]
        play_notes(notes, 0, False)
    else:
        print('already playing')

def stop_playing():
    global playing
    if playing:
        playing = False
        print('stop playing')
    else:
        print('nothing playing')

Button(root, text='Start', command=start_playing).pack(padx=10, pady=10)
Button(root, text='Stop', command=stop_playing).pack(padx=10, pady=10)

这只是一个示例,您可以根据需要进行修改。

于 2019-01-03T07:22:21.790 回答