2015-08-08 149 views
0

我的代码写成如下。它完美的作品。现在我想将文字输出保存在文本文件中。Python使用PyAudio如何将麦克风输出写入文本文件并在接收端读取以创建波形文件

p = pyaudio.PyAudio() 

stream = p.open(format=pyaudio.paInt16, 
      channels=18, 
      rate=44100, 
      input=True, 
      frames_per_buffer=1024, 
      output_device_index=1) 

for i in range(0, 1000): 
data = stream.read(CHUNK) 
frames.append(data) 

stream.stop_stream() 
stream.close() 
p.terminate() 

target = open('target.txt', 'w') 
target.write(repr(frames)) 
target.close() 

它将输出保存在文本文件中,如下所示。 (具有列表由逗号sepereted STR元件。

Ex - ['' , '' , '']. 


['\x00\x00\x00\x00\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc9\x00\xb2\xfe\x82\x02\xf7\ts\xfen\x00i\xff\xeb\xff\xa9\xff\xed\xff\xc5\xff\xd1\xff\xcd\xff\xaf\xff\xde\xff\xb8\xff\xc9\xff\xb0\xff\xca\xff\xd1\xff\xc9\xff\xcb\xff\xdf\xff\xdb\xff\xe2\xff\xe6\xff\xd9\xff\xf8\xff\xe1\xff\xf6\xff\xf1\xff\xd8\xff\xe1\xff\xe4\xff\xd4\xff\xdd\xff\xef\xff\xef\xff\xdc\xff\xd2\xff\xd6\xf ....] 

在接收机侧我传送该文件。

接收机打开文本文件。使用eval()函数转换的内容。

  with open("targetRec.txt",'r') as inf:  
       Rnewdiffdict = eval(inf.read()) 

inf.Read()返回字符串对象。Eval返回列表对象。 以下代码将列表写入wave文件。

  wf = wave.open("recaudio.wav", 'wb') 
      wf.setnchannels(int(recmetadata[0])) 
      wf.setsampwidth(int(recmetadata[2])) 
      wf.setframerate(int(recmetadata[3])) 
      wf.writeframes(b''.join(Rnewdiffdict))  
      # Write frames in wave file . 
      wf.close() # Close wave file. 

现在,在发件人端,我想在发送时用''替换\ x。它可以减少文本文件的大小。

  target.write(repr(frames).replace('\\x',' ')) 

在接收端,我想用\ x替换''来重新创建文件,因为它是在发送端的替换操作之前。

  Rnewdiffdict = eval(inf.read().replace(' ','\\x')) 

它给了我错误,然后程序挂起。

Traceback (most recent call last): 
    File "I:\Users\Administrator\Desktop\read wave.py", line 239, in <module> 
ReceiveAudio() 
    File "I:\Users\Administrator\Desktop\read wave.py", line 101, in ReceiveAudio 
    Rnewdiffdict = eval(inf.read().replace(' ','\\x')) 
    File "<string>", line 1 

回答

0

我在发送方替换了代码,如下所示。

target = open('target.txt', 'w')  
encoded_string = base64.b64encode(repr(frames)) ## Encode using base64 
target.write(encoded_string) 

在接收端代码编写如下 -

with open("targetRec.txt",'r') as inf: 
     x = inf.read() 
     y = x.decode('base64')    ## Decode using base64 
     z = eval(y) 
+0

是否有替代方式。 –

相关问题