Asked  1 Year ago    Answers:  5   Viewed   193 times

How can I play an .mp3 and a .wav file in my Java application? I am using Swing. I tried looking on the internet, for something like this example:

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

But, this will only play .wav files.

The same with:

http://www.javaworld.com/javaworld/javatips/jw-javatip24.html

I want to be able to play both .mp3 files and .wav files with the same method.

 Answers

1

Java FX has Media and MediaPlayer classes which will play mp3 files.

Example code:

String bip = "bip.mp3";
Media hit = new Media(new File(bip).toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();

You will need the following import statements:

import java.io.File;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
Tuesday, June 1, 2021
 
4

I'm not sure why the second approach you linked to starts another thread; I believe the audio will be played in its own thread anyway. Is the problem that your application finishes before the clip has finished playing?

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.LineEvent.Type;

private static void playClip(File clipFile) throws IOException, 
  UnsupportedAudioFileException, LineUnavailableException, InterruptedException {
  class AudioListener implements LineListener {
    private boolean done = false;
    @Override public synchronized void update(LineEvent event) {
      Type eventType = event.getType();
      if (eventType == Type.STOP || eventType == Type.CLOSE) {
        done = true;
        notifyAll();
      }
    }
    public synchronized void waitUntilDone() throws InterruptedException {
      while (!done) { wait(); }
    }
  }
  AudioListener listener = new AudioListener();
  AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(clipFile);
  try {
    Clip clip = AudioSystem.getClip();
    clip.addLineListener(listener);
    clip.open(audioInputStream);
    try {
      clip.start();
      listener.waitUntilDone();
    } finally {
      clip.close();
    }
  } finally {
    audioInputStream.close();
  }
}
Sunday, June 13, 2021
 
3
public static byte [] getAudioDataBytes(byte [] sourceBytes, AudioFormat audioFormat) throws UnsupportedAudioFileException, IllegalArgumentException, Exception{
        if(sourceBytes == null || sourceBytes.length == 0 || audioFormat == null){
            throw new IllegalArgumentException("Illegal Argument passed to this method");
        }

        ByteArrayInputStream bais = null;
        ByteArrayOutputStream baos = null;
        AudioInputStream sourceAIS = null;
        AudioInputStream convert1AIS = null;
        AudioInputStream convert2AIS = null;

        try{
            bais = new ByteArrayInputStream(sourceBytes);
            sourceAIS = AudioSystem.getAudioInputStream(bais);
            AudioFormat sourceFormat = sourceAIS.getFormat();
            AudioFormat convertFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, sourceFormat.getSampleRate(), 16, sourceFormat.getChannels(), sourceFormat.getChannels()*2, sourceFormat.getSampleRate(), false);
            convert1AIS = AudioSystem.getAudioInputStream(convertFormat, sourceAIS);
            convert2AIS = AudioSystem.getAudioInputStream(audioFormat, convert1AIS);

            baos = new ByteArrayOutputStream();

            byte [] buffer = new byte[8192];
            while(true){
                int readCount = convert2AIS.read(buffer, 0, buffer.length);
                if(readCount == -1){
                    break;
                }
                baos.write(buffer, 0, readCount);
            }
            return baos.toByteArray();
        } catch(UnsupportedAudioFileException uafe){
            //uafe.printStackTrace();
            throw uafe;
        } catch(IOException ioe){
            //ioe.printStackTrace();
            throw ioe;
        } catch(IllegalArgumentException iae){
            //iae.printStackTrace();
            throw iae;
        } catch (Exception e) {
            //e.printStackTrace();
            throw e;
        }finally{
            if(baos != null){
                try{
                    baos.close();
                }catch(Exception e){
                }
            }
            if(convert2AIS != null){
                try{
                    convert2AIS.close();
                }catch(Exception e){
                }
            }
            if(convert1AIS != null){
                try{
                    convert1AIS.close();
                }catch(Exception e){
                }
            }
            if(sourceAIS != null){
                try{
                    sourceAIS.close();
                }catch(Exception e){
                }
            }
            if(bais != null){
                try{
                    bais.close();
                }catch(Exception e){
                }
            }
        }
    }

Here sourceBytes represents MP3 file or WAV file. audioFormat is PCM format in which you want conversion. Also we need to put mp3spi.jar, tritonus_mp3.jar, jl*.jar, tritonus_share.jar from javazoom.com in classpath. Hope this may help to other.

Java 7 version:

public static byte [] getAudioDataBytes(byte [] sourceBytes, AudioFormat audioFormat) throws UnsupportedAudioFileException, IllegalArgumentException, Exception {
    if(sourceBytes == null || sourceBytes.length == 0 || audioFormat == null){
        throw new IllegalArgumentException("Illegal Argument passed to this method");
    }

    try (final ByteArrayInputStream bais = new ByteArrayInputStream(sourceBytes);
         final AudioInputStream sourceAIS = AudioSystem.getAudioInputStream(bais)) {
        AudioFormat sourceFormat = sourceAIS.getFormat();
        AudioFormat convertFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, sourceFormat.getSampleRate(), 16, sourceFormat.getChannels(), sourceFormat.getChannels()*2, sourceFormat.getSampleRate(), false);
        try (final AudioInputStream convert1AIS = AudioSystem.getAudioInputStream(convertFormat, sourceAIS);
             final AudioInputStream convert2AIS = AudioSystem.getAudioInputStream(audioFormat, convert1AIS);
             final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            byte [] buffer = new byte[8192];
            while(true){
                int readCount = convert2AIS.read(buffer, 0, buffer.length);
                if(readCount == -1){
                    break;
                }
                baos.write(buffer, 0, readCount);
            }
            return baos.toByteArray();
        }
    }
}

Maven:

<dependency>
    <groupId>com.googlecode.soundlibs</groupId>
    <artifactId>mp3spi</artifactId>
    <version>1.9.5-1</version>
</dependency>
<dependency>
    <groupId>com.googlecode.soundlibs</groupId>
    <artifactId>jlayer</artifactId>
    <version>1.0.1-1</version>
    <exclusions>
        <exclusion>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </exclusion>
    </exclusions>
</dependency>
Thursday, July 29, 2021
 
Nickool
 
4

Read your wave file @ http://java.sun.com/javase/technologies/desktop/media/jmf/ and encode to mp3 @ http://openinnowhere.sourceforge.net/lameonj/

As pointed out, lameonj is not a pure java solution. For that the options don't seem so many, but see the other SO question: MP3 Encoding in Java

Wednesday, August 11, 2021
 
iceduck
 
5

In the end I found code to do exactly what I wanted in Chapter 10 of the book Swing Hacks.

Thursday, September 23, 2021
 
zIs
 
zIs
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :