安装pyaudio
sudo apt-get install python-pyaudio python3-pyaudio
声音录制
import pyaudioimport wavedef record_audio(wave_out_path,record_second): CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 44100 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) print("设置参数完毕") print("开始录制声音") # int(RATE / CHUNK * record_second)录制时间内,需要读取多少次数据 # CHUNK一次采样数据多少 # RATE一秒采样多少 for _ in range(0, int(RATE / CHUNK * record_second)): data = stream.read(CHUNK) wf.writeframes(data) print("录制完成") stream.stop_stream() stream.close() p.terminate() wf.close()if __name__ == '__main__': record_audio("output.wav",record_second=4)
声音播放
import pyaudioimport wavefrom tqdm import tqdmdef play_audio(wave_path): CHUNK = 1024 wf = wave.open(wave_path, 'rb') # instantiate PyAudio (1) p = pyaudio.PyAudio() # open stream (2) stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True) # read data data = wf.readframes(CHUNK) # play stream (3) datas = [] while len(data) > 0: data = wf.readframes(CHUNK) datas.append(data) for d in tqdm(datas): stream.write(d) # stop stream (4) stream.stop_stream() stream.close() # close PyAudio (5) p.terminate()if __name__ == '__main__': play_audio("output.wav")
在执行其他程序时同时播放音频,可以使用回调的方式播放
import pyaudioimport wavefrom tqdm import tqdmimport timedef play_audio_callback(wave_path): CHUNK = 1024 wf = wave.open(wave_path, 'rb') # instantiate PyAudio (1) p = pyaudio.PyAudio() def callback(in_data, frame_count, time_info, status): data = wf.readframes(frame_count) return (data, pyaudio.paContinue) # open stream (2) stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True, stream_callback=callback) # read data stream.start_stream() while stream.is_active(): time.sleep(0.1) # stop stream (4) stream.stop_stream() stream.close() # close PyAudio (5) p.terminate()play_audio_callback("output.wav")