How to loop-play an audio with pyaudio?

試著忘記壹切 提交于 2020-01-06 06:05:28

问题


I want to play an audio wave file using Pyaudio and tkinter where the audio plays when the button is pressed and the audio stops when the stop button is pressed. Now, the audio is a simple 5 secs wave file, as it is suppose to, the audio stops after 5 secs. I would like to know how to loop it, such that the audio keeps on playing forever unless the stop button is clicked. I cannot find a way with this code.

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()

回答1:


A way to loop-play the audio is to define a function loop_play that will execute play_audio in loop and pass this function as target of the thread:

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()


来源:https://stackoverflow.com/questions/47513950/how-to-loop-play-an-audio-with-pyaudio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!