无需在Python上写入磁盘即可加入.wav文件

时间:2018-05-24 19:58:50

标签: python python-3.x wave

我有一个二进制格式的.wav文件列表(它们来自websocket),我想加入一个二进制.wav文件然后用它进行语音识别。我已经能够使用以下代码:

audio = [binary_wav1, binary_wav2,..., binary_wavN] # a list of .wav binary files coming from a socket
audio = [io.BytesIO(x) for x in audio]

# Join wav files
with wave.open('/tmp/input.wav', 'wb') as temp_input:
    params_set = False
    for audio_file in audio:
        with wave.open(audio_file, 'rb') as w:
            if not params_set:
                temp_input.setparams(w.getparams())
                params_set = True
            temp_input.writeframes(w.readframes(w.getnframes()))

# Do speech recognition
binary_audio = open('/tmp/input.wav', 'rb').read())
ASR(binary_audio)

问题是我不想在磁盘中写入文件'/tmp/input.wav'。没有在磁盘中写入任何文件,有没有办法做到这一点?

感谢。

2 个答案:

答案 0 :(得分:3)

拥有文件但从不将其放入磁盘的一般解决方案是流。为此,我们使用io库,它是用于处理内存流的默认库。您甚至已经在代码中使用BytesIO了。

audio = [binary_wav1, binary_wav2,..., binary_wavN] # a list of .wav binary files coming from a socket
audio = [io.BytesIO(x) for x in audio]

# Join wav files

params_set = False
temp_file = io.BytesIO()
with wave.open(temp_file, 'wb') as temp_input:
    for audio_file in audio:
        with wave.open(audio_file, 'rb') as w:
            if not params_set:
                temp_input.setparams(w.getparams())
                params_set = True
            temp_input.writeframes(w.readframes(w.getnframes()))

#move the cursor back to the beginning of the "file"
temp_file.seek(0)
# Do speech recognition
binary_audio = temp_file.read()
ASR(binary_audio)

注意我没有任何.wav文件可以试用。它可以通过wave库来正确处理实际文件和缓冲流之间的差异。

答案 1 :(得分:0)

使用scipy和numpy,您可以将wav文件读取为numpy数组,而不是进行所需的修改。

from scipy.io import wavfile
import numpy as np

# load files
_, arr1 = wavfile.read('song.wav')
_, arr2 = wavfile.read('Aaron_Copland-Quiet_City.wav')

print(arr1.shape)
print(arr2.shape)

>>> (1323001,)
>>> (1323000,)

# make new array by concatenating two audio waves
new_arr = np.hstack((arr1, arr2))
print(new_arr.shape)

>>> (2646001,)

# save new audio wave
wavfile.write('new_audio.wav')