【问题标题】:How to loop-play an audio with pyaudio?如何使用 pyaudio 循环播放音频?
【发布时间】:2018-05-10 20:52:33
【问题描述】:

我想使用 Pyaudio 和 tkinter 播放音频文件,按下按钮时播放音频,按下停止按钮时音频停止。现在,音频是一个简单的 5 秒波形文件,正如假设的那样,音频在 5 秒后停止。我想知道如何循环播放它,这样除非单击停止按钮,否则音频会一直播放下去。我找不到使用此代码的方法。

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

# --- classes ---

def play_audio():
    global is_playing
    global my_thread
    chunk = 1024
    wf = wave.open('sound.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()

【问题讨论】:

  • while True 循环。

标签: python loops audio tkinter pyaudio


【解决方案1】:

一种循环播放音频的方法是定义一个函数loop_play,它将在循环中执行play_audio,并将这个函数作为线程的目标传递:

def loop_play():
    while is_playing:
        play_audio()

def press_button_play():
    global is_playing
    global my_thread

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

【讨论】:

  • 不使用全局变量可以实现吗?
  • @Maxtron 是的,如果你把你的应用放在一个类中并用类属性替换全局变量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多