[Python] Play wav file in callback mode [Pyaudio / Python]

Discussão em 'Python' iniciado por Stack, Fevereiro 6, 2025.

  1. Stack

    Stack Membro Participativo

    I wanna play wav file using PyAudio with callback mode. I could play wav file once but then stops. For example, if I want to play a wav file (trumpet sound, etc.) every five seconds, how should I implement this? Also, lemme know how to play array (wav data) in callback mode, just in case.

    The code that I've implemented so far in the following...

    import pyaudio
    import numpy as np
    import wave
    import time

    FORMAT = pyaudio.paInt16
    CHANNEL = 2
    CHUNK = 1024
    RATE = 44100

    flag = True
    cur_dt = 0

    # reading wav file here
    wf = wave.open('test_3.wav', 'rb')

    # instantiate PyAudio (1)
    p = pyaudio.PyAudio()

    # define callback (2)
    def callback(in_data, frame_count, time_info, status):

    global flag, cur_dt, wf

    if flag:
    wf = wave.open('test_3.wav', 'rb')
    flag = False

    data = np.zeros((frame_count,), dtype=np.int16)
    data = wf.readframes(frame_count)

    # convert bytes to int
    data_int = np.frombuffer(data, dtype=np.int16)\

    # convert int to float
    data_float = data_int.astype(np.float32) / 32768.0

    # # convert float to int
    # data_int_again = (data_float*32768.0).astype(np.int16, order='C')

    # ur processing...
    f1 = np.fft.fft(data_float)
    f2 = np.fft.ifft(f1)
    f3 = (f2*32768.0).astype(np.int16)

    # make it sound!
    data = f3

    # cur_dt += 1
    # print(cur_dt)

    return (data.tobytes(), pyaudio.paContinue)


    # open stream using callback (3)
    stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
    channels=wf.getnchannels(),
    rate=wf.getframerate(),
    output=True,
    stream_callback=callback)

    # print(p.get_format_from_width(wf.getsampwidth())) # paInt16
    # print(wf.getsampwidth()) # 3
    # print(wf.getnchannels()) # 2
    # print(wf.getframerate()) # 44100

    stream.start_stream()

    # wait for stream to finish (5)
    while stream.is_active():
    time.sleep(5)
    flag = True

    # stop stream (6)
    stream.stop_stream()
    stream.close()
    wf.close()

    # close PyAudio (7)
    p.terminate()

    Continue reading...

Compartilhe esta Página