我在设置按钮时遇到问题,该按钮在按下时会播放音频。
我在按钮上使用tkinter
,在音频上使用simpleaudio
。
x = ""
def audio(file):
x = file
return x
window = tk.Tk()
window.title("Audio")
audio_button = tk.Button(window,text="Audio Test",command=audio("imposter")).pack(side="left")
audio_button1 = tk.Button(window,text="Audio Test Two",command=audio("crewmate")).pack(side="left")
stop_all = tk.Button(window,text="Stop All",command=audio("stop"),fg="red").pack(side="left")
tk.mainloop()
while True:
if not x == "stop":
if x == "crewmate":
wave_obj = sa.WaveObject.from_wave_file("File here")
play_obj = wave_obj.play()
while play_obj.is_playing():
if x == "stop":
break
else:
pass
elif x == "imposter":
wave_obj = sa.WaveObject.from_wave_file("File here")
play_obj = wave_obj.play()
while play_obj.is_playing():
if x == "stop":
break
else:
pass
else:
pass
也可以帮助缩短代码
答案 0 :(得分:1)
pack
返回None,因此,当需要保留对小部件的引用时,应将链式打包链接到小部件的创建。
这是解决您问题的一种可能方法;我没有简单的音频,所以不能保证代码完全正确;带有simpleaudio
调用的代码行已被注释掉,并且print语句使您可以验证逻辑。您将必须取消注释它们,然后尝试。
逻辑在启动新文件之前停止所有音频;您可能希望使其更加用户友好,例如,如果命令请求同一首歌曲,则让歌曲结束,而不是重新启动它。
# import simpleaudio as sa
import tkinter as tk
def stop_audio():
print('stopping all')
# sa.stopall()
def test_audio(state):
if state == 'imposter':
path = "path/to/imposter.wav"
elif state == 'crewmate':
path = "path/to/crewmate.wav"
else:
return
# wave_obj = sa.WaveObject.from_wave_file(path)
stop_audio()
# play_obj = wave_obj.play()
print(f'playing {state}')
window = tk.Tk()
window.title("Audio")
audio_button = tk.Button(window,text="Audio Test", command=lambda state='imposter': test_audio(state))
audio_button.pack(side="left")
audio_button1 = tk.Button(window,text="Audio Test Two", command=lambda state='crewmate': test_audio(state))
audio_button1.pack(side="left")
stop_all = tk.Button(window,text="Stop All",fg="red", command=stop_audio)
stop_all.pack(side="left")
tk.mainloop()