Zulko / moviepy

Video editing with Python
https://zulko.github.io/moviepy/
MIT License
12.1k stars 1.51k forks source link

Extracted mp3 file is longer than the original mp4 file. #2032

Closed Pimool closed 10 months ago

Pimool commented 10 months ago

Hi, I'm trying to extract audio from mp4 file and save it as mp3 file with using moviepy.

However, the playtime of mp3 file(output) and mp4 file(input) are different.

I guess it's a problem of fps, but I cannot handle it.

from moviepy.editor import *

clip = VideoFileClip('video.mp4')
print(clip.fps)
print(clip.duration)
audio_clip = clip.audio
print(audio_clip.fps)
print(audio_clip.duration)
audio_clip.write_audiofile('audio.mp3', logger = None)
audio_clip.close()
clip.close()

Output :

29.97002997002997
2322.28
44100
2322.28

The converted audio(mp3) file's playtime is 39:41 while video(mp4) file's playtime is 38:42

I'm trying to make a transcript of video file by converting into mp3 file, so the time difference is very crucial to me.

Can anyone help?

Pimool commented 10 months ago

With a lot of search, I found the solution.

It's a problem with ffmpeg.

Pass '-write_xing 0' as a ffmpeg parameter.

Example :

from moviepy.editor import *

clip = VideoFileClip('video.mp4')
audio_clip = clip.audio
audio_clip.write_audiofile('audio.mp3', logger = None, ffmpeg_params = ["-write_xing", "0"])

You can also use it when using pydub.

from pydub import AudioSegment

audio = AudioSegment.from_mp3(audio_file_path)
audio.export(path, format = 'mp3', parameters = ["-write_xing", "0"])

References https://superuser.com/questions/607703/wrong-audio-duration-with-ffmpeg https://trac.ffmpeg.org/ticket/2697