python - 使用 stream.write 从流中回放
问题描述
我正在尝试制作一个脚踏开关来控制 PC 上的录音。来自脚踏开关的输入进入一个通道(控制通道),来自音乐家的输入将进入另一个通道。这些通道与声卡的 Line-in 相连。当从脚踏开关检测到某些动作时,程序应该从音乐家的频道开始录音,然后播放。下面的程序可以工作,但是当使用 stream.write(...) 播放录制的流时,它的播放速度比原来的快。我是 Python 的初学者,所以我的编程很糟糕!
import pyaudio
import time
import numpy as np
CHUNK = 1024 #Bytes
CHANNELS = 2 #Channels
RATE = 44100 #Frames/sec
FORMAT = pyaudio.paFloat32 #Frame= 4Bytes/channel
p = pyaudio.PyAudio()#instatiates PyAudio object which sets up the portaudio system
# open stream object as input & output-to record/play audio
stream = p.open(format=FORMAT,
channels=CHANNELS,
input_device_index=1,
output_device_index=3,
rate=RATE,
input=True,
output=True,
frames_per_buffer=CHUNK)
record_seconds = int(input("Give me recording time: "))
print("* recording")
pressed = [] #intitialize array to store duration that the footswitch is pressed
count=0 #counts press of footswitch
s=0 #counts short press of footswitch
l=0 #counts long press of footswitch
i=0 #time divisions of the buffer
frames = [] #initialize array to record frames
while i <= int(RATE / CHUNK * record_seconds):#44100x4Bytes/1024 per channel
data = stream.read(CHUNK,exception_on_overflow=False)#read audio data from the stream
sIN = np.frombuffer(data, dtype = np.float32)#creates an array of floats from the buffer
ctrlCH=sIN[2::CHANNELS]
sCTRL=np.sqrt(np.sum(ctrlCH**2))
rightCH=sIN[1::CHANNELS]
dataR=rightCH.tobytes()
if(sCTRL>0.5):
count = count + 1
else:
count = 0
pressed.append(count)
if(i>1):
if (pressed[i-1]>=3 and pressed[i-1]<=10 and pressed[i]<3):
s=s+1
if (s==1):
print("Recording ",s, "...")
elif (s==2):
print ("Stopped recording")
if(s==1):
frames.append(dataR) #store data
elif (s==2):
stream.write(b''.join(frames))# write the frames as bytes
i+=1
print("* done")
time.sleep(1)
stream.stop_stream()#pause playing/recording
stream.close()#terminate the stream
p.terminate()#terminate portaudio session
这可能是因为 stream.open() 用于两个通道,但 stream.write() 用于一个通道,使其以双倍速率记录。
解决方案
推荐阅读
- cross-compiling - 在 ubuntu 20 上编译内核 3.xx
- r - 在装扮的 SVM 函数上调整参数时出现未使用的参数错误
- c - 构建带有负节点的表达式树
- python - 从 10 个输出到 25 个输出 CNN,但修改后的代码不起作用?
- python - 需要 Cpanel SQLite 3.8.3 或更高版本(找到 3.7.17)
- javascript - 在 ReactJS 中获取 onComponentDidMount 期间出现 CORS 错误
- reactjs - Firebase Firestore 未接收数据库中的输入/返回,带有材料 ui 和反应
- jquery - 为什么没有身份就不能添加事件
- javascript - 已解决 : ReactJS : Uncaught TypeError: Cannot read property 'id' of undefined 使用 axios 发布到 Laravel 控制器时
- delphi - 设置字体设置不适用于创建动态标签