如何在Python中修改错误的mp3歌曲长度
我正在使用mutagen来修改一个文件的元数据,文件名是“temp.mp3”。
这首歌的时长是3分钟。
当我尝试以下代码时:
from mutagen.mp3 import MP3
audio = MP3('temp.mp3')
print audio.info.length
audio.info.length = 180
print audio.info.length
audio.save()
audio = MP3('temp.mp3')
print audio.info.length
我得到了下面的输出:
424.791857143
180
424.791857143
看起来mp3的保存方法没有把我存储在info.length里的信息记录下来。请问我该怎么做才能把这些数据保存到文件里呢?
1 个回答
0
这个问题很早就有人问过,但我最近也遇到了同样的情况。
经过一番努力在网上搜索,我找到了这个答案,它使用ffmpeg这个工具来修复错误的元数据。
希望下面的解决方案能帮到某些人,节省一些时间。
我们可以用ffmpeg来复制文件,并自动修复有问题的元数据,使用这个命令:
ffmpeg -v quiet -i "sound.mp3" -acodec copy "fixed_sound.mp3"
这里的-v quiet
选项是为了让它在运行时不在控制台上打印命令的详细信息。
要检查你是否已经安装了ffmpeg,可以在命令行输入ffmpeg -version
。如果没有安装,可以从这里下载:https://ffmpeg.org/
我下面写了一个函数,应该能解决这个问题!
import os
def fix_duration(filepath):
## Create a temporary name for the current file.
## i.e: 'sound.mp3' -> 'sound_temp.mp3'
temp_filepath = filepath[ :len(filepath) - len('.mp3')] + '_temp' + '.mp3'
## Rename the file to the temporary name.
os.rename(filepath, temp_filepath)
## Run the ffmpeg command to copy this file.
## This fixes the duration and creates a new file with the original name.
command = 'ffmpeg -v quiet -i "' + temp_filepath + '" -acodec copy "' + filepath + '"'
os.system(command)
## Remove the temporary file that had the wrong duration in its metadata.
os.remove(temp_filepath)