I want to play many input data from a microphone without buffering. I tried, but there is buffering. Here is my code.
import pyaudio
import wave
import urllib.request
import struct
import numpy as np
import sounddevice as sd
import matplotlib.pyplot as plt
# Callback function---------------------------------
def callback(indata, outdata, frames, time, status):
# if status:
# print(status)
outdata[:] = indata
#---------------------------------------------------
# Parameters ----------------------------------------------
Window_Size = 22050 # Point
FORMAT_D = pyaudio.paFloat32; FORMAT_W = pyaudio.paInt32
CHANNELS = 1 # Mono
Sample_Rate = 22050 # Hz
dT = 1/Sample_Rate
RECORD_SECONDS = 20 # s
NOFFRAMES = int(Sample_Rate/Window_Size * RECORD_SECONDS)
WAVE_OUTPUT_FILENAME = "output.wav"
#-----------------------------------------------------------
p = pyaudio.PyAudio()
stream_D = p.open(format=FORMAT_D,
channels=CHANNELS,
rate=Sample_Rate,
input=True,
frames_per_buffer=Window_Size)
stream_W = p.open(format=FORMAT_W,
channels=CHANNELS,
rate=Sample_Rate,
input=True,
frames_per_buffer=Window_Size)
print("* recording")
frames = []
# "I think the problem appears from here"------------------------------
for i in range(0, int(Sample_Rate/Window_Size * RECORD_SECONDS)):
data_D = stream_D.read(Window_Size)
# data_W = stream_W.read(Window_Size)
decoded = np.fromstring(data_D, 'Float32')
# np.savetxt(str(i)+'ttt.txt',transform)
sd.play(decoded,22050)
# frames.append(data_W)
#-------------------------------------------------------
print("* done recording")
stream_D.stop_stream()
stream_D.close()
p.terminate()
#plt.plot(transform)
#plt.show()
# Save as a wave file---------------------------
#wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
#wf.setnchannels(CHANNELS)
#wf.setsampwidth(p.get_sample_size(FORMAT_W))
#wf.setframerate(Sample_Rate)
#wf.writeframes(b''.join(frames))
#wf.close()
#-------------------------------------------
This code performs to save input data from a microphone at 1s intervals, transform byte data to nparray data (np.transform()), and play the data with a speaker (sd.play()). This code works, but there is buffering when for loop start again. I want to play the sound from a microphone smoothly. When I asked first, someone recommended to use callback function, so I added it, But, I don't know how to use it. How do I get rid of the buffering? Is there some examples? Should I use Threads or multiprocessing?
The delay is due to buffer size ... you will get a negligible delay using a 1k buffer as per
# Window_Size = 22050 # Point
Window_Size = 1024 # Point
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.