WAV音訊檔案按秒切片段

酱_油發表於2024-05-01

wav音訊檔案按秒切片段

import wave

def split_wav_by_seconds(input_file, output_file, start_second, end_second):
    with wave.open(input_file, 'rb') as wf:
        framerate = wf.getframerate()
        num_frames = wf.getnframes()
        num_channels = wf.getnchannels()
        sample_width = wf.getsampwidth()

        start_frame = int(start_second * framerate)
        end_frame = int(end_second * framerate)

        with wave.open(output_file, 'wb') as output_wf:
            output_wf.setnchannels(num_channels)
            output_wf.setsampwidth(sample_width)
            output_wf.setframerate(framerate)

            wf.setpos(start_frame)
            output_wf.writeframes(wf.readframes(end_frame - start_frame))

        print(f"Saved {output_file}")

# 示例用法
input_file = "./vocals.wav"    # 輸入音訊檔名
output_file = "./output.wav"  # 輸出檔名
start_second =  38           # 擷取的起始秒數
end_second = 51              # 擷取的結束秒數

split_wav_by_seconds(input_file, output_file, start_second, end_second)

相關文章