Fix audio drifts in video records with Kdenlive and FFmpeg

I recorded some old VHS tapes to digitize them to video movies and burn them on DVDs. Sadly the audio had a shift or drift of around one and a half second over the one hour video. Here a small solution to fix this problem with the help of Kdenlive and FFmpeg.

My example is a record.mp4 file.

Extract audio with FFmpeg

The following command will extract the audio of the MPEG-4 into a WAV file.

ffmpeg -i record.mp4 -vn audio.wav

The extracted audio should be available as audio.wav file.

Detect audio drift

We can easily detect the audio drift by importing record.mp4 and audio.wav into Kdenlive via drag and drop.

Kdenlive import media

Stretch the audio with FFmpeg

On the screenshot above is visible that record.mp4 and audio.wav have different length. My Kdenlive has shows the length in hours, minutes, seconds and at the end a twenty-fifth of a second.

filehmss/25
record.mp400455402
audio.wav00455306

I can calculate for both file the amount of 1/25 seconds with the following formular. Please note that s/25 is something like a variable for a twenty-fifth of a second.

(((60 * h) + m) * 60 + s) * 25 + s/25
filecalculationresult in s/25
record.mp4(((60 * 0) + 45) * 60 + 54) * 25 + 268852
audio.wav(((60 * 0) + 45) * 60 + 53) * 25 + 668831

Calculate the speedup with python

We can calculate the speedup for the audio with Python for example. The only important thing is that the calculator has enough digits, cause the result will be very close to 1.0. And important is that we divide the amount of s/25 from audio.wav by the amount of s/25 from record.mp4.

python
Python 2.7.13 (default, Jan 19 2017, 14:48:08)
[GCC 6.3.0 20170118] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 68831.0 / 68852.0
0.9996949979666531

FFmpeg filter tempo

We strech the audio.wav file with the following command and the factor from above. The command will write the result to the file audio_streched.wav.

ffmpeg -i audio.wav -filter:a atempo="0.9996949979666531" audio_streched.wav

Afterwards we import audio_streched.wav into Kdenlive via drag and drop and delete audio.wav. Video and audio should have now the same length.

Kdenlive streched audio

Combine video with streched audio

Drag the record.mp4 source to Video channel and click in the menu item Clip on Split Audio.

Kdenlive split audio

Afterwards click in the menu item Timeline on Ungroup Clips and delete the audio channel. There should be just a muted video channel now. Drag the audio_streched.wav source into the Audio channel.

Kdenlive render video

We can now render the video with the streched audio to an mp4 file with the button Render.

Kdenlive render
Next Previous