Crop MP3 to last N seconds

789 views Asked by At

I want to generate a new (fully valid) MP3 file from an existing MP3 file. The new file should only contain the last N seconds of the track.

There's -t option in avconv for getting first N seconds:

-t duration (output)

Stop writing the output after its duration reaches duration. duration may be a number in seconds, or in "hh:mm:ss[.xxx]" form.

Is there an option to crop last N seconds? avconv is not requirement in my case, all other tools are acceptable.

2

There are 2 answers

0
Chamath On BEST ANSWER

You can simply use ffprobe to get the duration of the audio.

ffprobe -i input_audio -show_entries format=duration -v quiet -of csv="p=0"

Calculate nth_second and use it with ffmpeg

ffmpeg -i input_audio -ss nth_second output_file

Following is the shell script for the process.

#!/bin/bash
duration=$(ffprobe -i ${1} -show_entries format=duration -v quiet -of csv="p=0")
nth_second=$(echo "${duration} - ${2}"|bc)
ffmpeg -i ${1} -ss ${nth_second} ${3}
0
pat_brat On

If you want to release the script, you should check to ensure mp3info is installed, and the argument count, etc. but this should get you started. Save it as a .sh and call it with mp3lastnsecs.sh input.mp3 output.mp3 numsecs

Also, you'll need to add the other ffmpeg flags for tagging, bitrate, etc.

#!/usr/bin/bash

SECS=$(mp3info -p "%S" $1)
if [ "$SECS" -ge "$3" ]; then
  START=$((SECS-$3))
else
  echo 'Error: requested length is longer than the song.'
  exit 1
fi

#echo Starting song $1 from $START seconds.
ffmpeg -i "$1" -ss $START "$2"

Sample output:

[  @  tmp] ./lastN.sh 01-glaube.mp3 output.mp3 20
Starting song 01-glaube.mp3 from 96 seconds.
ffmpeg -i 01-glaube.mp3 -ss 96 output.mp3 # I had an echo in there for testing, it now calls ffmpeg directly
[  @  tmp] ./lastN.sh 01-glaube.mp3 output.mp3 1234
Error: requested length is longer than the song.