1.下载相应的库
pip install moviepy
2.从视频中提取音频
from moviepy.editor import VideoFileClip
# 保存视频的根目录
root_path = 'C:/xxxx/'
# 保存转成音频切片的根目录
root_slice_path = 'C:/xxxx/slice'
#从视频提取音频
video = VideoFileClip(f"{root_path}video.mp4")
audio = video.audio
# 存到audio.wav中,audio.wav是自己命名的
audio.write_audiofile(f"{root_path}audio.wav")
3.将音频切片并保存
# 加载音频文件
audio = AudioSegment.from_file(f"{root_path}audio.wav")
# 定义每个片段的长度(以毫秒为单位)
segment_length = 100000 # 100 秒
segments = []
for start in range(0, len(audio), segment_length):
end = start + segment_length
segment = audio[start:end]
segment.export(f"{root_slice_path}segment_{start // 1000}.wav", format="wav")
directory = Path(f'{root_slice_path}')
pattern = '*.wav'
def extract_number(filename):
return int(''.join(filter(str.isdigit, filename)))
slice_results = sorted([f'{directory}/{f}' for f in os.listdir(directory) if fnmatch.fnmatch(f, pattern)], key=extract_number)