Java detecting an audio file (mp3)

2019-04-01 01:55发布

问题:

I have this code that reads an mp3 file

import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;

    public class Sound {
        public static void main(String[] args) {
            File sampleFile = new File("test.mp3");
            try {
                AudioSystem.getAudioFileFormat(sampleFile);
            } catch (UnsupportedAudioFileException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

The problem here is that it is returning file not supported exception, the file here is an mp3 file. Java doesn't support mp3 files? if so what are others to validate an audio file?(like ogg, wav)

回答1:

You may take a look at Apache Tika library. It can detect type of a file by its content and extract file metadata. It supports mp3 format.

Here is an example of file type detection with Apache Tika.



回答2:

You need to add MP3SPI library so that java audio api could recognize and decode mp3 files.