Python中如何将录制生成的.wav音频文件保存到指定目录
修改PyAudio录音输出路径的实现方法
原代码默认将wav文件存在脚本所在目录,本质是因为传入wave.open()的参数只有文件名、没有带目标存储路径,程序会默认使用当前工作目录作为存储位置,只需要修改文件路径参数即可实现自定义目录保存,有两种常用实现方式:
方式一:直接写全文件绝对路径
直接将wav_output_filename变量的值改为带目标目录的完整文件路径即可。
- Windows系统示例:注意路径前加
r标记为原始字符串,避免反斜杠被识别为转义字符
# 替换原代码中wav_output_filename的赋值即可,路径改成你自己的目标目录 wav_output_filename = r'D:\audio_records\test1.wav'
- macOS/Linux系统示例:
wav_output_filename = '/home/yourname/audio_records/test1.wav'
注意:使用这种方式需要提前手动创建好目标目录,
wave模块本身不会自动创建不存在的文件夹,目录不存在时运行会抛出路径不存在错误。
方式二:用os模块拼接路径(跨平台兼容,推荐)
使用Python内置的os模块处理路径,可以自动适配不同操作系统的路径分隔符,还可以加一行代码自动创建不存在的目标目录,不用手动提前建文件夹。
修改后的完整代码如下:
import pyaudio import wave import os # 导入内置os模块处理路径 form_1 = pyaudio.paInt16 chans = 1 # 1 channel samp_rate = 48000 chunk = 1024 record_secs = 2 dev_index = 2 # 自定义目标保存目录,替换为你自己的路径即可 save_directory = r'D:\audio_records' # 自动拼接目录和文件名,跨平台自动适配路径格式 wav_output_filename = os.path.join(save_directory, 'test1.wav') # 自动创建目标目录,目录已存在时不会报错 os.makedirs(save_directory, exist_ok=True) audio = pyaudio.PyAudio() # create pyaudio instantiation # create pyaudio stream stream = audio.open(format = form_1,rate = samp_rate,channels = chans, \ input_device_index = dev_index,input = True, \ frames_per_buffer=chunk) print("recording") frames = [] # loop through stream and append audio chunks to frame array for ii in range(0,int((samp_rate/chunk)*record_secs)): data = stream.read(chunk) frames.append(data) print("finished recording") # stop the stream, close it, and terminate the pyaudio instantiation stream.stop_stream() stream.close() audio.terminate() # save the audio frames as .wav file wavefile = wave.open(wav_output_filename,'wb') wavefile.setnchannels(chans) wavefile.setsampwidth(audio.get_sample_size(form_1)) wavefile.setframerate(samp_rate) wavefile.writeframes(b''.join(frames)) wavefile.close()
改动点说明
- 新增
os模块导入,不需要额外安装第三方依赖 - 单独定义存储目录变量,后续修改路径只需要改这一个值
os.makedirs加exist_ok=True参数,自动补全不存在的目录,避免路径错误- 用
os.path.join拼接路径,Windows、macOS、Linux系统下都可以正常运行,不需要手动修改路径分隔符
内容的提问来源于stack exchange,提问作者Ditto-Gatto
相关产品推荐
相关产品推荐

