The duration of an audio file is often provided as a property of AudioFileFormat
. From the docs:
The following table lists some common properties that should be used in implementations:
Audio File Format Properties
+-------------+------------+-----------------------------------------------+
|Property key | Value type | Description |
|-------------|------------|-----------------------------------------------|
| "duration" | Long | playback duration of the file in microseconds |
| "author" | String | name of the author of this file |
| "title" | String | title of this file |
| "copyright" | String | copyright message |
| "date" | Date | date of the recording or release |
| "comment" | String | an arbitrary text |
+-------------+------------+-----------------------------------------------+
Note the should, meaning they are optional.
Also note, duration
is given in microseconds, not milliseconds!
So to get the duration of an audio file in Java, you could call:
final String DURATION = "duration";
Long duration = (Long)audioFileFormat.properties().get(DURATION);
// and because duration is optional, use a fallback
// for uncompressed formats like AIFF and WAVE
if (duration == null
&& audioFileFormat.getFormat().getEncoding() == PCM_SIGNED
// make sure we actually have a frame length
&& audioFileFormat.getFrameLength() != NOT_SPECIFIED
// make sure we actually have a frame rate
&& audioFileFormat.getFormat().getFrameRate() != NOT_SPECIFIED
// check if this is WAVE or AIFF, other uncompressed formats may work as well
&& (audioFileFormat.getType() == WAVE || audioFileFormat.getType() == AIFF)) {
duration = (long) (audioFileFormat.getFrameLength() / audioFileFormat.getFormat().getFrameRate() * 1000L * 1000L);
}
This snippet would get you the duration in microseconds either from the duration
property or from frame length and frame rate. The latter is only useful for uncompressed formats like WAVE or AIFF.
Since mp3 is not supported by current JVMs out of the box, you need to install an mp3 codec. This comes in the form of a service provider implementing the Service Provider Interface (SPI). A pure Java implementation of the SPI for mp3 is the Tritonus library. For usage with Maven, see for example here. Note that the library has apparently been abandoned a long time ago. A more current package, using CoreAudio for Mac is CASampledSP. Another library, based on FFmpeg and written for Mac and Windows, is FFSampledSP (full disclosure: I'm the author of both these libraries).
Another, slightly more unconventional way to get the duration, is to use JavaFX, as it supports mp3 out of the box:
import java.io.File;
import javafx.scene.media.Media;
import javafx.util.Duration;
final Media media = new Media(new File("somefile.mp3").toURI().toString());
final Duration duration = media.duration();