首页 > 解决方案 > 使用 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() 用于一个通道,使其以双倍速率记录。

标签: pythonstreampyaudio

解决方案


推荐阅读