Python 根据歌词时间戳切割歌曲
操作
1.查看歌词时间戳格式
2.代码实现
#!/user/bin/env python
# _*_coding:utf-8_*_
from pydub import AudioSegment
import re
with open("C:/Users/悟空传 (2020重唱版)",'r',encoding='utf-8') as f: #打开歌词文件
time_list = []
lyric_list = []
#循环获取每一句歌词时间戳,
while True:
line = f.readline()
if not line:
break
line = line.strip('\n')
p = '(?<=\[)[^]]+'
b = re.findall(p,line)
time_list.append(b[0])
# print(line.split(']')[1])
if line.split(']')[1]=="": #获取无效音频
s = 'sil' #无效音频
# print(s)
lyric_list.append(s)
else:
# print(line.split(']')[1])
lyric_list.append(line.split(']')[1])
print(len(time_list))
print(len(lyric_list))
with open('C:/Users/Desktop/test.txt','w+') as f: #截取音频名称与歌词保存位置
cout = 0
for i,j in zip(range(len(time_list)),lyric_list):
cout += 1
start_time = time_list[i] # 获取开始截取时间戳
print(start_time)
if i < len(time_list) - 1:
stop_time = time_list[i + 1] # 获取结束时间戳
print(stop_time)
file_name = "C:/Users/悟空传 (2020重唱版).mp3" # 歌曲保存路径
sound = AudioSegment.from_mp3(file_name)
print("time:", start_time, "~", stop_time)
start_time = (float(start_time.split(':')[0]) * 60 + float(start_time.split(':')[1])) * 1000 + float(
'0.{}'.format(start_time.split('.')[-1])) * 100 # 开始时间转换为毫秒
stop_time = (float(stop_time.split(':')[0]) * 60 + float(stop_time.split(':')[1])) * 1000 + float(
'0.{}'.format(stop_time.split('.')[-1])) * 100 # 结束时间转换为毫秒
print("ms:", start_time, "~", stop_time) # 打印 开始时间与结束时间
word = sound[start_time:stop_time] # 截取
f.write("{}.mp3".format(cout)+'\t'+j+"\n") #截取的音频名字与对应歌打印
word.export('C:/Users/{}.mp3'.format(cout), format="mp3", # 保存位置
tags={'artist': 'AppLeU0', 'album': cout})
3.保存结果展示