Reproducción.mp3 y.wav en Java?


¿Cómo puedo reproducir un archivo .mp3 y un .wav en mi aplicación Java? Estoy usando Swing. Intenté buscar en Internet algo como este ejemplo:

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();
    }
}

Pero, esto solo reproducirá archivos .wav.

Lo mismo con:

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

Quiero poder reproducir ambos archivos .mp3 y .wav con el mismo método.

Author: SpaceCore186, 2011-05-18

12 answers

Java FX tiene clases Media y MediaPlayer que reproducirán archivos mp3.

Código de ejemplo:

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

Necesitará las siguientes declaraciones de importación:

import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
 102
Author: jasonwaste,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-04 00:21:12

Escribí un reproductor de mp3 java puro: mp3transform.

 30
Author: Thomas Mueller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-31 17:55:40

Puedes jugar .wav solo con java API:

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

Código:

AudioInputStream audioIn = AudioSystem.getAudioInputStream(MyClazz.class.getResource("music.wav"));
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();

Y play .mp3 con JLayer

 17
Author: Gustavo Marques,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-21 17:03:30

Ha pasado un tiempo desde que lo usé, pero JavaLayer es ideal para la reproducción de MP3

 15
Author: Mark Heath,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-19 10:34:49

Recomendaría usar BasicPlayerAPI. Es de código abierto, muy simple y no requiere JavaFX. http://www.javazoom.net/jlgui/api.html

Después de descargar y extraer el archivo zip, se deben agregar los siguientes archivos jar a la ruta de compilación del proyecto:

  • basicplayer3. 0.jar
  • todos los frascos del directorio lib (dentro de BasicPlayer3.0)

Aquí hay un uso minimalista ejemplo:

String songName = "HungryKidsofHungary-ScatteredDiamonds.mp3";
String pathToMp3 = System.getProperty("user.dir") +"/"+ songName;
BasicPlayer player = new BasicPlayer();
try {
    player.open(new URL("file:///" + pathToMp3));
    player.play();
} catch (BasicPlayerException | MalformedURLException e) {
    e.printStackTrace();
}

Importaciones requeridas:

import java.net.MalformedURLException;
import java.net.URL;
import javazoom.jlgui.basicplayer.BasicPlayer;
import javazoom.jlgui.basicplayer.BasicPlayerException;

Eso es todo lo que necesitas para empezar a reproducir música. El reproductor está iniciando y administrando su propio hilo de reproducción y proporciona funcionalidad reproducir, pausar, reanudar, detenery buscar.

Para un uso más avanzado puede echar un vistazo al reproductor de música jlGui. Es un clon de WinAmp de código abierto: http://www.javazoom.net/jlgui/jlgui.html

La primera clase a mirar sería PlayerUI (dentro del paquete javazoom.jlgui.jugador.amplificador). Demuestra las características avanzadas del BasicPlayer bastante bien.

 12
Author: Ivo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-10 16:24:23

Usando javax estándar.API de sonido, una sola dependencia Maven, completamente de código abierto ( Java 7 requerido):

Pom.xml

 <!-- 
    We have to explicitly instruct Maven to use tritonus-share 0.3.7-2 
    and NOT 0.3.7-1, otherwise vorbisspi won't work.
   -->
<dependency>
  <groupId>com.googlecode.soundlibs</groupId>
  <artifactId>tritonus-share</artifactId>
  <version>0.3.7-2</version>
</dependency>
<dependency>
  <groupId>com.googlecode.soundlibs</groupId>
  <artifactId>mp3spi</artifactId>
  <version>1.9.5-1</version>
</dependency>
<dependency>
  <groupId>com.googlecode.soundlibs</groupId>
  <artifactId>vorbisspi</artifactId>
  <version>1.0.3-1</version>
</dependency>

Código

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine.Info;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

import static javax.sound.sampled.AudioSystem.getAudioInputStream;
import static javax.sound.sampled.AudioFormat.Encoding.PCM_SIGNED;

public class AudioFilePlayer {

    public static void main(String[] args) {
        final AudioFilePlayer player = new AudioFilePlayer ();
        player.play("something.mp3");
        player.play("something.ogg");
    }

    public void play(String filePath) {
        final File file = new File(filePath);

        try (final AudioInputStream in = getAudioInputStream(file)) {

            final AudioFormat outFormat = getOutFormat(in.getFormat());
            final Info info = new Info(SourceDataLine.class, outFormat);

            try (final SourceDataLine line =
                     (SourceDataLine) AudioSystem.getLine(info)) {

                if (line != null) {
                    line.open(outFormat);
                    line.start();
                    stream(getAudioInputStream(outFormat, in), line);
                    line.drain();
                    line.stop();
                }
            }

        } catch (UnsupportedAudioFileException 
               | LineUnavailableException 
               | IOException e) {
            throw new IllegalStateException(e);
        }
    }

    private AudioFormat getOutFormat(AudioFormat inFormat) {
        final int ch = inFormat.getChannels();

        final float rate = inFormat.getSampleRate();
        return new AudioFormat(PCM_SIGNED, rate, 16, ch, ch * 2, rate, false);
    }

    private void stream(AudioInputStream in, SourceDataLine line) 
        throws IOException {
        final byte[] buffer = new byte[4096];
        for (int n = 0; n != -1; n = in.read(buffer, 0, buffer.length)) {
            line.write(buffer, 0, n);
        }
    }
}

Referencias:

 9
Author: odoepner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-03 12:08:12

La forma más fácil que encontré fue descargar el archivo jar de JLayer desde http://www.javazoom.net/javalayer/sources.html y añadirlo a la biblioteca Jar http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29

Aquí está el código para la clase

public class SimplePlayer {

    public SimplePlayer(){

        try{

             FileInputStream fis = new FileInputStream("File location.");
             Player playMP3 = new Player(fis);

             playMP3.play();

        }  catch(Exception e){
             System.out.println(e);
           }
    } 
}

Y aquí están las importaciones

import javazoom.jl.player.*;
import java.io.FileInputStream;
 4
Author: Vlad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-13 15:44:12

Para dar a los lectores otra alternativa, estoy sugiriendo JACo MP3 Player library, un reproductor de mp3 java multiplataforma.

Características:

  • muy bajo uso de CPU (~2%)
  • increíble pequeña biblioteca (~90KB)
  • no necesita JMF (Java Media Framework)
  • fácil de integrar en cualquier aplicación
  • fácil de integrar en cualquier página web (como applet).

Para obtener una lista completa de sus métodos y atributos, puede consultar su documentación aquí.

Código de ejemplo:

import jaco.mp3.player.MP3Player;
import java.io.File;

public class Example1 {
  public static void main(String[] args) {
    new MP3Player(new File("test.mp3")).play();
  }
}

Para más detalles, he creado un tutorial simple aquí que incluye un código fuente descargable.

 3
Author: Mr. Xymon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-04 13:13:40

Primero debe instalar JMF (descargar usando este enlace)

File f = new File("D:/Songs/preview.mp3");
MediaLocator ml = new MediaLocator(f.toURL());
Player p = Manager.createPlayer(ml);
p.start();

No olvides agregar archivos jar JMF

 2
Author: Kasun Shamentha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-09 17:06:46

Hacer una búsqueda de freshmeat.net para la biblioteca JAVE (significa Java Audio Video Encoder) (enlace aquí ). Es una biblioteca para este tipo de cosas. No se si Java tiene una función mp3 nativa.

Probablemente necesitará envolver la función mp3 y la función wav juntas, usando herencia y una función de envoltura simple, si desea que un método ejecute ambos tipos de archivos.

 1
Author: Spencer Rathbun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-25 20:28:17

Para agregar soporte de lectura MP3 a Java Sound, agregue el mp3plugin.jar del JMF a la ruta de clase en tiempo de ejecución de la aplicación.

Tenga en cuenta que la clase Clip tiene limitaciones de memoria que la hacen inadecuada para más de unos segundos de sonido de alta calidad.

 0
Author: Andrew Thompson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-08 09:20:28

Utilice esta biblioteca: import sun.audio.*;

public void Sound(String Path){
    try{
        InputStream in = new FileInputStream(new File(Path));
        AudioStream audios = new AudioStream(in);
        AudioPlayer.player.start(audios);
    }
    catch(Exception e){}
}
 0
Author: Akila Lekamge,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-24 20:04:24