安装包 pyaudio 安装pyaudio真是曲折的过程……
直接用pip安装会报错
1 2 python3 -m pip install pyaudio > fatal error: 'portaudio.h' file not found
所以要先用brew下portaudio,但是我的homebrew死活无法下载portaudio
1 2 brew install portaudio > no formulae found
试过重启什么的都不行,最后重新安装了homebrew
1 2 3 cd /usr/local /Homebrew/Library/Taps/homebrew/rm -rf homebrew-core git clone https://github.com/Homebrew/homebrew-core.git
然后就成功安装了portaudio,但是安装pyaudio依然报错失败,尝试link
但是显示已经link了,仍然无法安装。
最后终于找到了方法,手动找到portaudio.h的位置‘usr/local/Cellar/portaudio/19.7.0/include’ ,然后以如下方式安装就可以啦
1 python3 -m pip install --global-option='build_ext' --global-option='-I/usr/local/Cellar/portaudio/19.7.0/include' --global-option='-L/usr/local/Cellar/portaudio/19.7.0/lib' pyaudio
playsound/pydub 这个就正常安装就没问题。
1 python3 -m pip install playsound pydub
播放音频 这个很简单。
1 2 3 from playsound import playsoundplaysound("chunk3.wav" )
另外一种方法
1 2 3 4 5 6 7 8 9 from pydub import AudioSegmentfrom pydub.playback import playsong = AudioSegment.from_wav("/Users/whitelephant/Files/ENN/发音/audio-chunks/chunk3.wav" ) play(song)
录音并生成文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 def record_audio (wave_out_path, record_second ): """ 录音功能 """ p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True , frames_per_buffer=CHUNK) wf = wave.open(wave_out_path, 'wb' ) wf.setnchannels(CHANNELS) wf.setsampwidth(p.get_sample_size(FORMAT)) wf.setframerate(RATE) for _ in range(0 , int(RATE * record_second / CHUNK)): data = stream.read(CHUNK) wf.writeframes(data) stream.stop_stream() stream.close() p.terminate() wf.close() filepath = 'try.wav' record_audio(filepath,10 )
Reference Python实现电脑录音(含音频基础知识讲解)
How to Play and Record Audio in Python