Python Tkinter按钮调用函数用PyAudio播放wave--崩溃

Python Tkinter按钮调用函数用PyAudio播放wave--崩溃,python,button,tkinter,crash,pyaudio,Python,Button,Tkinter,Crash,Pyaudio,我一按下按钮,它就会一直按下,程序就会崩溃。但声音确实在播放。我在PyAudio网站上直接使用代码,所以我有点困惑为什么它会崩溃 from tkinter import * import pyaudio import wave import sys root = Tk() root.title("Compose-O-Matic") root.geometry("400x300") def play_audio(): chunk = 1024 wf = wave.open('m

我一按下按钮,它就会一直按下,程序就会崩溃。但声音确实在播放。我在PyAudio网站上直接使用代码,所以我有点困惑为什么它会崩溃

from tkinter import *
import pyaudio
import wave
import sys

root = Tk()
root.title("Compose-O-Matic")
root.geometry("400x300")

def play_audio():
    chunk = 1024
    wf = wave.open('misc_environment3.wav', 'rb')
    p = pyaudio.PyAudio()

    stream = p.open(
        format = p.get_format_from_width(wf.getsampwidth()),
        channels = wf.getnchannels(),
        rate = wf.getframerate(),
        output = True)

    data = wf.readframes(chunk)

    while data != '':
        stream.write(data)
        data = wf.readframes(chunk)

    stream.stop_stream()
    stream.close()
    p.terminate()

app = Frame(root)
app.grid()

button_start = Button(app, text = ">", command = play_audio)
button_start.grid()

root.mainloop()

使用
threading
播放音乐

from tkinter import *
import pyaudio
import wave
import sys
import threading

# --- classes ---

def play_audio():
    global is_playing
    chunk = 1024
    wf = wave.open('misc_environment3.wav', 'rb')
    p = pyaudio.PyAudio()

    stream = p.open(
        format = p.get_format_from_width(wf.getsampwidth()),
        channels = wf.getnchannels(),
        rate = wf.getframerate(),
        output = True)

    data = wf.readframes(chunk)

    while data != '' and is_playing: # is_playing to stop playing
        stream.write(data)
        data = wf.readframes(chunk)

    stream.stop_stream()
    stream.close()
    p.terminate()

# --- functions ---

def press_button_play():
    global is_playing
    global my_thread

    if not is_playing:
        is_playing = True
        my_thread = threading.Thread(target=play_audio)
        my_thread.start()

def press_button_stop():
    global is_playing
    global my_thread

    if is_playing:
        is_playing = False
        my_thread.join()

# --- main ---

is_playing = False
my_thread = None

root = Tk()
root.title("Compose-O-Matic")
root.geometry("400x300")

button_start = Button(root, text="PLAY", command=press_button_play)
button_start.grid()

button_stop = Button(root, text="STOP", command=press_button_stop)
button_stop.grid()

root.mainloop()

您是否收到任何错误消息?可能问题是函数工作时间太长,mainloop无法完成它的工作-使用
线程
。我应该如何使用线程来实现这一点?我尝试过使用“class AudioFile(threading.Thread):”或甚至将play audio函数放入threading.Thread()的线程类中,但仍然得到了相同的结果。我想问题可能是while循环没有中断,但代码直接来自PyAudio文档(当我注释掉while循环时不会崩溃,当然文件不会播放)。我更改了代码以添加停止按钮,并且
正在播放
以停止线程内的音乐。