cue和wav音乐文件的歌曲分割提取
ai辅助快速开发
通过百度的文小言辅助,自己修修改改的cue和wav音乐文件,需要先本地安装ffmpeg,如果不在path环境,可以自己写ffmpeg的全路径地址。
代码:
[Python] 纯文本查看 复制代码import re
import subprocess
def parse_cue(cue_file_path):
tracks = []
current_track = None
with open(cue_file_path, 'r', encoding='GB2312') as file:
for line in file:
line = line.strip()
# 检查是否为新的音轨开始
if line.startswith('TRACK'):
if current_track:
tracks.append(current_track)
match = re.match(r'TRACK (\d+) AUDIO', line)
if match:
track_number = int(match.group(1))
current_track = {'number': track_number, 'title': '', 'start': None, 'end': None}
# 提取歌曲名
elif line.startswith('TITLE'):
title = line.split('TITLE "')[1].split('"')[0]
if current_track:
current_track['title'] = title
# 提取起始时间
elif line.startswith('INDEX 01'):
match = re.match(r'INDEX 01 ((\d+):(\d+):(\d+))', line)
if match:
# minutes, seconds, frames = map(int, match.groups())
# 将时间转换为毫秒
# total_seconds = minutes * 60 + seconds + frames / 75.0
# start_time = int(total_seconds * 1000)
start_time,minutes,seconds,ms = match.groups()
if current_track:
current_track['start'] = minutes+":"+ seconds+"."+ms
# 注意:.cue文件通常不直接包含结束时间,但可以通过下一个音轨的起始时间推断
# 添加最后一个音轨(如果有)
if current_track:
tracks.append(current_track)
return tracks
def split_audio(wav_file, tracks):
""" 根据 CUE 文件中的时间信息分割 WAV 文件 """
for i, track in enumerate(tracks):
print(i, track)
start_time = track['start']
if (len(tracks) == i+1):
# 如果是到文件末尾,则不需要指定结束时间
end_cmd = ''
end_time = ''
else:
# 如果是第一个音轨,没有前一个音轨的结束时间,所以从头开始
next_track = tracks[i+1] # 获取前一个音轨的信息(注意索引)
end_cmd = '-to'
end_time = next_track['start']
# 使用 ffmpeg 剪切音频
output_file = track['title'].strip()+".wav"
print(' '.join(['ffmpeg', '-ss', start_time, end_cmd, end_time, '-i', wav_file, '-y', '-vn', '-acodec', 'copy', output_file]))
subprocess.run([
'ffmpeg', '-ss', start_time, end_cmd, end_time, '-i', wav_file, '-y', '-vn', '-acodec', 'copy', output_file
])
# 使用示例
cue_file_path = './1.cue'
wav_file = './1.wav'
tracks = parse_cue(cue_file_path)
for track in tracks:
print(f"Track {track['number']}: {track['title']}, Start: {track['start']}")
# 注意:这里没有打印结束时间,因为它通常需要从下一个音轨的起始时间推断
confirm = input('确认分割音频:')
if confirm.lower() == 'y' or confirm.lower() == 'yes':
split_audio(wav_file, tracks)
else:
print("你已取消cue音频提取执行")