The html5 video tag has a loop attribute. When playing a video in a continuous loop, it doesn't do this seamlessly. I hear cracks and pops at the beginning. With ffmpeg I am able to trim .05 seconds from the start and end to make audio and video uniform. That helped a lot but still not fully smooth when played in a loop. Then crossfade came into question. How can I gradually lower the volume at the end of video and gradually raise the volume at the beginning?

ffmpeg .05 seconds from the start and end

for f in *.mp4; do
    duration=$(ffmpeg -i "$f" 2>&1 | grep "Duration"| cut -d ' ' -f 4 | sed s/,//)
    length=$(echo "$duration" | awk '{ split($1, A, ":"); print 3600*A[1] + 60*A[2] + A[3] }' )
    trim_end=$(echo "$length" - .05 - "$trim_start" | bc)
    echo ffmpeg -ss "$trim_start" -i "$f" -c copy -map 0 -t "$trim_end" "${f%.mp4}-trimmed.mp4"
  • Why are you not just using ffprobe to get the duration? – llogan Jun 12 '15 at 7:22
  • @LordNeckBeard, yes I will change it to ffprobe for duration. However is there a way to decrease audio in the last 30 frames or second? – Code_Ed_Student Jun 12 '15 at 11:57

For purposes of this answer I'll assume the audio is encoded with an aac codec.

For each video:

Use ffmpeg to extract the sound track to its own file.

ffmpeg -i "${f%.mp4}" -vn -acodec copy "${f%-sound.aac}"

If not yet known, determine the duration of the audio file. In some cases ffmpeg is known to give an incorrect duration (https://stackoverflow.com/questions/10437750/how-to-get-the-real-actual-duration-of-an-mp3-file-vbr-or-cbr-server-side), so I'd use sox.

duration=$(sox soundtrack_before_processing.mp3 -n stat 2>&1 | sed -n 's#^Length (seconds):[^0-9]*\([0-9.]*\)$#\1#p')

Use sox to apply fades in and out.

sox "${f%-sound.aac}" "${f%-sound-with-fades.aac}" fade t $fade_in_seconds $duration $fade_out_seconds

Replace the audio track in the original video file with the faded track.

ffmpeg -y -i "${f%.mp4}" -i "${f%-sound-with-fades.aac}" -map 0:v -map 1 -vcodec copy -acodec aac -strict experimental -shortest "${%f-new.mp4}"
  • Why you are using sox when same can be done with ffmpeg? – Paul B. Mahol Feb 15 '16 at 16:50
  • I was using sox rather than ffmpeg because of the SO question listed in the answer, which notes an issue with ffmpeg related to getting the actual duration of an audio stream. Granted, that may be dependent upon which code was used to encode the stream. – Mark Schneider Feb 16 '16 at 17:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.