Pythonでオーディオデータをスライスする
Pythonでは、waveモジュールを使用してオーディオデータの一部を切り出すことができます。以下にオーディオデータの一部を切り出す方法を示すサンプルコードを示します。
import wave
def extract_audio_segment(input_file, output_file, start_seconds, end_seconds):
# 打开输入音频文件
with wave.open(input_file, 'rb') as audio_file:
# 获取音频文件的参数
num_channels = audio_file.getnchannels()
sample_width = audio_file.getsampwidth()
frame_rate = audio_file.getframerate()
num_frames = audio_file.getnframes()
# 计算截取的起始帧和结束帧
start_frame = int(start_seconds * frame_rate)
end_frame = int(end_seconds * frame_rate)
# 限制截取范围在有效帧数内
start_frame = min(start_frame, num_frames)
end_frame = min(end_frame, num_frames)
# 移动文件指针到起始帧
audio_file.setpos(start_frame)
# 计算截取的帧数
num_frames_to_extract = end_frame - start_frame
# 打开输出音频文件
with wave.open(output_file, 'wb') as output_audio:
# 设置输出音频文件的参数
output_audio.setnchannels(num_channels)
output_audio.setsampwidth(sample_width)
output_audio.setframerate(frame_rate)
# 从输入音频文件中读取并写入截取的音频数据
output_audio.writeframes(audio_file.readframes(num_frames_to_extract))
使用例:
input_file = 'input.wav'
output_file = 'output.wav'
start_seconds = 3.5
end_seconds = 8.2
extract_audio_segment(input_file, output_file, start_seconds, end_seconds)
上記のコードは、入力オーディオファイルから3.5秒目から8.2秒目のオーディオデータを切り取り、出力オーディオファイルに保存します。実行前にWaveモジュールのインストールが必須です。