以下是一个保存音频文件的代码示例,使用Python的wave模块:
import wave
def save_audio_file(input_audio, output_filename, sample_width, sample_rate, channels):
# 打开输出文件并设置参数
with wave.open(output_filename, 'wb') as output_file:
output_file.setnchannels(channels)
output_file.setsampwidth(sample_width)
output_file.setframerate(sample_rate)
# 写入音频数据
output_file.writeframes(input_audio)
# 示例用法
input_audio = b'\x00\x01\x02\x03' # 这里的input_audio是一个二进制音频数据
output_filename = 'output.wav'
sample_width = 2 # 每个样本的字节数(2表示16位)
sample_rate = 44100 # 采样率
channels = 2 # 声道数
save_audio_file(input_audio, output_filename, sample_width, sample_rate, channels)
上述代码中,save_audio_file
函数接受输入音频数据(以二进制形式传入),输出文件名以及音频的样本宽度、采样率和声道数等参数。然后,它使用wave模块创建一个新的音频文件,并设置正确的参数。最后,将输入音频数据写入输出文件。
请注意,上述代码示例假设输入音频数据是以16位格式编码的。如果你的音频数据以其他格式编码(例如8位、32位浮点数等),你需要相应地更改sample_width
的值,并确保输入的音频数据与其兼容。
此外,上述示例中的输出文件格式是.wav,你也可以根据需要更改为其他音频格式,然后使用相应的模块进行处理。
上一篇:保存应用的条件格式