pyaudio在windows和mac上录不到声音

强烈推荐python-sounddevice的录音方法,见本文结尾。该方法可以在pycharm等IDE中使用。

转载网上的程序见附录,但是在mac和windows上运行都没声音,网上查了很多,没有找到关键点,之后设置参数得到解决。

  1. windows解决方法:
    将通道数(CHANNELS)设为2,windows上有声音录到了。
  2. Mac解决方法:
conda update --force conda

然后重新安装

conda install pyaudio

再去终端运行程序就可以了,推测是mac新系统(10.15)导致conda的包不兼容了。
【注意:是在base环境中更新的cobda,不确定在anaconda其他的虚拟环境中这样做是否有用。总之更新之后,base和其他虚拟环境都没问题了。
想到更新conda,是因为在base中安装pyaudio总是报错:

RemoveError: 'setuptools' is a dependency of conda and cannot be removed from conda's operating environment.

pip卸载并用conda重装setuptools没用,于是强制更新conda。(https://www.cnblogs.com/hellojiaojiao/p/10872421.html)
最后结果是前面的两个问题同时解决。】
注意:不能用IDE,只能在终端运行才能录到声音。

转载的附录:


```python
# -*- coding:utf-8 -*-
import pyaudio
import wave
input_filename = "input.wav"               # 麦克风采集的语音输入
input_filepath = "."                                # 输入文件的path
in_path = os.path.join(input_filepath, input_filename)


def get_audio(filepath):
    aa = str(input("是否开始录音?   (是/否)"))
    if aa == str("是"):
        CHUNK = 256
        FORMAT = pyaudio.paInt16
        CHANNELS = 1                # 声道数
        RATE = 16000                # 采样率
        RECORD_SECONDS = 10
        WAVE_OUTPUT_FILENAME = filepath
        p = pyaudio.PyAudio()

        stream = p.open(format=FORMAT,
                        channels=CHANNELS,
                        rate=RATE,
                        input=True,
                        frames_per_buffer=CHUNK)

        print("*"*10, "开始录音:请在10秒内输入语音")
        frames = []
        for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
            data = stream.read(CHUNK)
            frames.append(data)
        print("*"*10, "录音结束\n")

        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()
    elif aa == str("否"):
        exit()
    else:
        print("无效输入,请重新选择")
        get_audio(in_path)

get_audio(in_path)

另外一种更友善的录音方式:
先安装python-sounddevice

import sounddevice as sd
from scipy.io.wavfile import write

fs = 44100  # Sample rate
seconds = 3  # Duration of recording

myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=1)
sd.wait()  # Wait until recording is finished
write('output.wav', fs, myrecording)  # Save as WAV file 

你可能感兴趣的:(Programming,python,windows,mac)