如何在python中保存修剪的wave文件?

时间:2015-12-23 21:11:29

标签: python numpy speech-recognition microphone wave

我正在尝试录制麦克风输入,执行一些端点算法,该算法将终止语音并保存新的波形文件仅用语音。

我设法保存了一个文件,但是当我播放录音时,它播放了一半的语音序列。

1)数组应采用什么格式才能成功保存?

2)如何将其转换为该格式?

我正在使用以下算法进行麦克风录音,错误是我保存文件的方式:

如果我调用writeframes(帧),它可以很好地保存完整的3秒麦克风输入。

FORMAT = pyaudio.paInt16                # We use 16bit format per sample
CHANNELS = 1
RATE = 44100
CHUNK = 1024                            # 1024bytes of data red from a buffer
RECORD_SECONDS = 3
WAVE_OUTPUT_FILENAME = "file.wav"

audio = pyaudio.PyAudio()

# start Recording
stream = audio.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE, input=True,
                    frames_per_buffer=CHUNK)

print "recording..."
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)
print "finished recording"
# stop Recordings
stream.stop_stream()
stream.close()
audio.terminate()

frames = ''.join(frames)

# important! convert from string to int
amplitudeSamples = np.fromstring(frames, np.int16)

# Perform endpointing algorithm where I compute start and end indexes 
# within amplitudeSamples array

voiceSample = amplitudeSamples[start:end]

# Here lies the problem
waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
waveFile.setnchannels(1)
waveFile.setsampwidth(2)
waveFile.setframerate(RATE)
waveFile.writeframes(voiceSample) 
#waveFile.writeframesraw(voiceSample) # doesn't work also
waveFile.close()

1 个答案:

答案 0 :(得分:2)

在编写之前将numpy数组转换为字符串:

wavFile.writeframes(voiceSample.tostring())