使用pyaudio录音

时间:2016-11-20 12:30:20

标签: python voice pyaudio

我正在尝试使用python录制语音。 我试图使用pyaudio模块,它在我的计算机上保存了一个wav文件,但录制了静态语音。 有什么建议吗?

import pyaudio
import wave

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "voice.wav"

p = pyaudio.PyAudio()

stream = p.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("* done recording")

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

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

4 个答案:

答案 0 :(得分:2)

首先,确保您的麦克风实际连接,打开而不是静音。

打开流时,您没有提供设备索引。这意味着您将获得PyAudio认为默认的设备。哪个可能不是你的麦克风。

在交互式Python会话中使用get_device_count对象的get_device_info_by_indexPyAudio方法。打印get_device_info_by_index返回的词典,以确定哪个设备索引代表您的麦克风,并在打开流时将该索引号提供为input_device_index参数。

答案 1 :(得分:0)

您的代码适用于我的环境:Win7和Python3.4 - 我使用笔记本电脑的麦克风录制我的声音。 也许你的麦克风的录音电平设置得太低了。或者是静音还是禁用?

答案 2 :(得分:0)

确保您的麦克风已连接到计算机。可以使用以下代码识别它。

import speech_recognition as sr
for index, name in enumerate(sr.Microphone.list_microphone_names()):
    print("Microphone with name \"{1}\" found for microphone(device_index{0})".format(index, name))

答案 3 :(得分:0)

下面的代码将列出可用记录设备的索引,然后用户可以指定特定的索引作为输入,代码将通过给定的记录设备索引开始记录。

import pyaudio
import wave

FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 512
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "recordedFile.wav"
device_index = 2
audio = pyaudio.PyAudio()

print("----------------------record device list---------------------")
info = audio.get_host_api_info_by_index(0)
numdevices = info.get('deviceCount')
for i in range(0, numdevices):
        if (audio.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0:
            print "Input Device id ", i, " - ", audio.get_device_info_by_host_api_device_index(0, i).get('name')

print("-------------------------------------------------------------")

index = (input())
print("recording via index "+str(index))

stream = audio.open(format=FORMAT, channels=CHANNELS,
                rate=RATE, input=True,input_device_index = index,
                frames_per_buffer=CHUNK)
print ("recording started")
Recordframes = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    Recordframes.append(data)
print ("recording stopped")

stream.stop_stream()
stream.close()
audio.terminate()

waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
waveFile.setnchannels(CHANNELS)
waveFile.setsampwidth(audio.get_sample_size(FORMAT))
waveFile.setframerate(RATE)
waveFile.writeframes(b''.join(Recordframes))
waveFile.close()