Mohamed Bawaneen
Mohamed Bawaneen

Reputation: 159

run mp3 and .aac vlc audio in java

I would like to run audio file from java and i read many codes in SO but unbale to run my file perhaps! Seems I have mentioned wrong path or using wrong lib . Please assist me what's wrong in below code to run mp3 or VLC .aac format file

  public void playSound() {
  try {
      AudioInputStream audioInputStream =  AudioSystem.getAudioInputStream(new File("D:/clinic/clinic/mysound.mp3").getAbsoluteFile());
     Clip clip = AudioSystem.getClip();
    clip.open(audioInputStream);
    clip.start();
 } catch(Exception ex) {
    System.out.println("Error with playing sound.");
    ex.printStackTrace();
}
}

Upvotes: 1

Views: 918

Answers (3)

9Lukas5
9Lukas5

Reputation: 81

The audioformats supported natively are nit that useful if you don't want to have huge audiofiles. I ended using WAV files as it was what I could get to work, but it bothered me all the time.

Using jaad was trickier than I thought, but I got it working now: Java play AAC encoded audio

Upvotes: 0

stelar7
stelar7

Reputation: 335

AudioSystem does not support .mp3 files. (Only AIFC, AIFF, AU, SND, and WAVE)

If you want to use .mp3 files, try using MediaPlayer instead.

// Fake init of JFX Toolkit (Just do this once before you use MediaPlayer) 
// Not needed in a JavaFX application as Application.launch() inits the toolkit 
new JFXPanel();  


Media media = new Media(new File("yourFile.mp3").toURI().toString());   
MediaPlayer player = new MediaPlayer(media);    
player.play();  

Upvotes: 2

Anonymous
Anonymous

Reputation: 179

If you use the this.getClass.getResource() method instead of the File(file) method, maybe it would work. Remember that the file that the audio is in has to be in the same package as the class that is running it. If this doesn't work, then try it with a .wav file(you can use a .mp3 to .wav converter).

public void run() {
    try {
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(this.getClass().getResource("mysound.mp3"));
        Clip clip = AudioSystem.getClip();
        clip.open(audioInputStream);
        clip.start();
        clip.loop(Clip.LOOP_CONTINUOUSLY);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

I hope this helps.

Upvotes: 2

Related Questions