To check the Аudio Length in a Java Spring Boot application, you can use the following open source libraries or tools.
1. Using AudioFileFormat
THIS OPTION DID NOT WORK FOR ME – It throws IOException: mark/reset not supported. You can use the javax.sound.sampled.AudioFileFormat
class to get the audio length.
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioFileFormat;
public class AudioLengthChecker {
public static void main(String[] args) throws Exception {
// Load the audio file
AudioInputStream ais = AudioSystem.getAudioInputStream(new FileInputStream("path_to_your_audio_file.wav"));
// Get the audio format
AudioFormat af = ais.getFormat();
// Calculate the length in milliseconds
int lengthInMs = (int) ais.getFrameLength() * af.getFrameSize();
// Convert the length to seconds
int lengthInSeconds = lengthInMs / 1000;
System.out.println("Audio length: " + lengthInSeconds + " seconds");
}
}
2. Using FFmpeg
You could use some library wrapper of Ffmpeg. It is a powerful tool for video, but audio also. Check out this stack overflow issue:
https://stackoverflow.com/questions/6239350/how-to-extract-duration-time-from-ffmpeg-output
I’ve used this tool before and you could read more here: https://programtom.com/dev/?s=Ffmpeg. I’ve also coded some wrapper apps: https://programtom.com/dev/product/video-converter-tool/
3 Using a third-party library jaudiotagger
I’ve used the jaudiotagger library. Here is the maven dependency:
<dependency> <groupId>net.jthink</groupId> <artifactId>jaudiotagger</artifactId> <version>3.0.1</version> </dependency>
And here is the working code:
try { AudioFile audioMetadata = AudioFileIO.read(new File(s)); System.out.println("Audio Metadata {} " + audioMetadata.displayStructureAsPlainText()); System.out.println(audioMetadata.getAudioHeader().getTrackLength()); System.out.println(audioMetadata.getAudioHeader().getPreciseTrackLength()); System.out.println(audioMetadata.getAudioHeader().getBitRate()); } catch (CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException e) { throw new RuntimeException("Error while getting metadata for audio file. Error " + e.getLocalizedMessage()); }
Note that the above code snippets are just examples and may need to be modified based on your specific requirements.