0

我的代码如下所示。它完美地工作。现在我想将麦克风的输出保存在文本文件中。

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()

它将输出保存在文本文件中,如下所示。(列表具有以逗号分隔的 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() 返回字符串 object 。eval 返回列表对象。以下代码将列表写入波形文件。

            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
4

1 回答 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)
于 2015-08-15T23:04:19.587 回答