在pyaudio / wave中录制和播放字节列表

时间:2014-07-30 15:42:51

标签: python wave looper pyaudio

我想使用pyaudio和wave lib录制和播放我的声音,但我不知道怎么做,因为wave lib需要一个文件的路径,即使我试图将它设置为带有列表的变量几秒前记录的字节,仍然无法工作因为我不能使用'read'作为列表。有人有点想法吗?我想做一个像KORG一样的looper等等

我希望在停止录制后立即播放,就像真正的looper一样,不会将记录保存为文件。

有我的代码(Python 3.4):

def record(self): #recording a voice

    #var for bytes from recording
    self.stream = self.player.open(format = self.FORMAT,
            channels = self.CHANNELS,
            rate = self.RATE,
            input = True,
            frames_per_buffer = self.CHUNK)

    print("Recording")

    self.frames = [] #byte list

    #recoring for a few seconds (5sec at this moment)
    for i in range(0, int(self.RATE / self.CHUNK * self.RECORD_SECONDS)):
        self.data = self.stream.read(self.CHUNK) #sing stream do data var
        self.frames.append(self.data) #add bytes to the end of a list
    print("Stop recording")

    self.stopRecording()

def stopRecording(self):

    self.stream.stop_stream()
    self.stream.close()
    print("Recording has been stopped")

    self.play()

def play(self): #playing a record
    print("Playing")


    f = wave.open(self.frames,"rb")  
    #read data  
    data = f.readframes(CHUNK)  

    #play stream  
    while data != '':  
        self.stream.write(data)  
        data = f.readframes(CHUNK)  

    self.stopPlaying()

1 个答案:

答案 0 :(得分:1)

停止记录后,您需要加入附加的数据,使用data = ''.join(self.frames),最后构建一个循环(for,while)来流式传输所有字节列表,以下是我的做法:

import pyaudio

chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 41000
RECORD_SECONDS = 5


p = pyaudio.PyAudio()

stream = p.open(format = FORMAT,
    channels = CHANNELS,
    rate = RATE,
    input = True,
    output = True,
    frames_per_buffer = chunk)



print ("***Recording***")

all = [] 

for i in range(0, RATE / chunk * RECORD_SECONDS):
     data = stream.read(chunk)
     all.append(data) 


print("***Stop recording***")


print ("***START PLAY***")


data = ''.join(all)


for i in range(0, len(data), chunk):
    stream.write(data[i:i+chunk])