Hola a todos, hoy os explicare como podemos reproducir ficheros de audio como mp3 en Java.
Lo primero que necesitaremos es el siguiente jar. Pincha aquí para descargarlo.
Este jar lo guardaremos donde queramos, lo recomendable es guardarlo dentro del proyecto.
Ahora en Eclipse, hacemos lo siguiente:
- Seleccionamos el proyecto que donde queramos usar este jar.
- Pinchamos en Project -> Properties -> Java Build Path.
- Pinchamos en el botón «Add External JARs»
- Buscamos el fichero jar.
- Aceptamos.
Ahora, debemos importar dos clases, las siguientes:
- javazoom.jl.decoder.JavaLayerException;
- javazoom.jl.player.Player;
La clase que usaremos se llama Player, al que le pasaremos un FileInputStream como parámetro. También es necesario que controlemos las siguientes excepciones:
- JavaLayerException
- IOException
Aquí os dejo un ejemplo, hecho en netbeans:
package reproductor; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javazoom.jl.decoder.JavaLayerException; import javazoom.jl.player.Player; /** * @author DiscoDurodeRoer */ public class Reproductor extends javax.swing.JFrame { /** * Creates new form Reproductor */ public Reproductor() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { btnReproducir = new javax.swing.JButton(); lblReproductor = new javax.swing.JLabel(); txtReproductor = new javax.swing.JTextField(); btnElegir = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); btnReproducir.setText("Reproductor"); btnReproducir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnReproducirActionPerformed(evt); } }); lblReproductor.setText("Reproductor"); btnElegir.setText("jButton2"); btnElegir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnElegirActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(46, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(lblReproductor) .addGap(18, 18, 18) .addComponent(txtReproductor, javax.swing.GroupLayout.PREFERRED_SIZE, 331, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnElegir, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(btnReproducir) .addGap(200, 200, 200)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(77, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblReproductor) .addComponent(txtReproductor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnElegir)) .addGap(30, 30, 30) .addComponent(btnReproducir) .addGap(53, 53, 53)) ); pack(); }// </editor-fold> private void btnElegirActionPerformed(java.awt.event.ActionEvent evt) { JFileChooser fc=new JFileChooser(); int seleccion=fc.showOpenDialog(this); if(seleccion==JFileChooser.APPROVE_OPTION){ File fichero=fc.getSelectedFile(); txtReproductor.setText(fichero.getAbsolutePath()); } } private void btnReproducirActionPerformed(java.awt.event.ActionEvent evt) { //Creamos el FileInputStream con la ruta del fichero de audio try(FileInputStream fis=new FileInputStream(txtReproductor.getText())){ //Creamos el objeto Player Player player=new Player(fis); //Reproducimos el fichero, una vez lo haga no podremos hacer nada hasta que termine player.play(); }catch (JavaLayerException e1) { JOptionPane.showMessageDialog(this, "No es un fichero de audio"); }catch (IOException ex) { Logger.getLogger(Reproductor.class.getName()).log(Level.SEVERE, null, ex); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Reproductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Reproductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Reproductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Reproductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Reproductor().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton btnElegir; private javax.swing.JButton btnReproducir; private javax.swing.JLabel lblReproductor; private javax.swing.JTextField txtReproductor; // End of variables declaration }
Pincha aquí para descargar el ejemplo para importar a tu IDE. Si usas eclipse puedes copiar las partes del código.
Si pruebas el código anterior y seleccionas un fichero de audio, veras que se reproduce pero no podemos hacer nada hasta que acabe la canción. Esto se debe a que debemos programar hilos, que es lo que se conoce como programación multihilo, lo veremos mas adelante.
Espero que os sea de ayuda. Si tenéis dudas, preguntad. Estamos para ayudarte.
No me funciona, :-(, estoy usando netbens y lo cierto es que soy muuuuy novato, acabo de arrancar :-).
Me he descargado lo que indicas, supongo que tambien me tengo que descargar el jar que indicas al principio, pero donde lo pongo?
los errores son en:
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
Solucionado, solo tenia que leer un poco mejor :-)
Hay que añadir el jar al projecto, en netbean es:
Boton derecho en libreria: Libraries>Add Jar/Folder
Muchas gracias, es un muy buen comienzo, a ver si consigo lo que quiero
Tengo un problemita al intentar reproducir el audio mp3 en mi .jar porque no lo encuentra y no entiendo por qué no lo encuentra?? Todo esta en el IDE NetBeans y al correrlo desde el mismo funciona sin problemas todo falla cuando intenta acceder al archivo mp3 y no lo encuentra
¿Como se obtiene la ruta del audio? Lo intenté como si fuera imagen, pero no funciona si hago la misma referencia
Agradeceria un poco de ayuda.
Esta es la clase que contola el audio
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package turnos;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
/**
*
* @author HERI
*/
public class Timbre {
private String filename;
private Player player;
public Timbre(String filename){
this.filename = filename;
}
public void close(){
if(player!= null){
player.close();
}
}
public void play(){
try{
FileInputStream fis = new FileInputStream(filename);
//InputStream path = getClass().getResourceAsStream(«src/mp3/BELL1.mp3»);
BufferedInputStream bis = new BufferedInputStream(fis);
player = new Player(bis);
} catch (FileNotFoundException | JavaLayerException ex) {
System.out.println(«Problema eproduciendo archivo «+filename);
System.out.println(ex);
}
new Thread(){
@Override
public void run(){
try{
player.play();
}catch(Exception ex){
System.out.println(ex);
}
}
}.start();
}
}
En seguida la principal que ejecuta la aplicaicon, en netbeans no tengo problema solo cuando creo el .jar no encuentra el audio
package turnos;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.awt.Color;
import java.awt.Font;
import java.awt.event.*;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javax.swing.Icon;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
/**
*
* @author HERIBERTO RIOS OLIVA
*/
public class Turnos extends JFrame implements ActionListener{
private JPanel panel;
private JTextField caja1,caja2;
private JLabel et1, et2;
private JButton btn1, btn2, btn3;
FileInputStream fis;
ImageIcon imagen;
Icon icon;
public Turnos(){
//títutlo de la pantalla
super(«Turnos pasaportes»);
Image icono = new ImageIcon(getClass().getResource(«/image/logo.png»)).getImage();
setIconImage(icono);
setLayout(null);
Font fuente = new Font(«TimesRoman», Font.BOLD,120);
Font fuente2 = new Font(«TimesRoman»,Font.PLAIN,90);
panel = new JPanel();
//Etiqueta 1
et1 = new JLabel(«Asignar turno:»);
et1.setBounds(0, 0, 130, 20);
//caja de texto
caja1 = new JTextField();
caja1.setBounds(100, 0, 90, 20);
caja2 = new JTextField();
caja2.setBounds(5, 30, 95, 150);
caja2.setBackground(Color.DARK_GRAY);
caja2.setForeground(Color.GREEN);
caja2.setFont(fuente2);
//Boton para asignar turno inicial
btn1 = new JButton(«Iniciar»);
btn1.setBounds(200, 0, 90, 20);
//Etiqueta donde se visualiza el turno
et2 = new JLabel(«000»);
et2.setBounds(100, 30, 250, 150);
et2.setForeground(Color.GREEN);
et2.setOpaque(true);
et2.setFont(fuente);
et2.setBackground(Color.DARK_GRAY);
//Boton pava avanzar de turno
btn2 = new JButton(«Siguiente >>»);
btn2.setBounds(100, 200, 130, 40);
//Boton sonido
btn3 = new JButton();
btn3.setBounds(250,200,100,40);
imagen = new ImageIcon(getClass().getResource(«/image/campana.png»));
icon = new ImageIcon(imagen.getImage().getScaledInstance(btn3.getWidth(), btn3.getHeight(), Image.SCALE_DEFAULT));
btn3.setIcon(icon);
//btn3 = new JButton(new ImageIcon(getClass().getResource(«/image/ico-imagen.jpg»)));
//agregar objetos a la pantalla
add(et1);
add(caja1);
add(btn1);
add(caja2);
add(et2);
add(btn2);
add(btn3);
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
add(panel);
setSize(400, 300);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String cadena;
int num,num2 ;
if(e.getSource() == btn1){
cadena = caja1.getText();
//Si la caja de texto esta vacia poner el foco hasta que ingrese un valor
if(cadena == null || cadena.equals(«») || cadena.isEmpty()){
JOptionPane.showMessageDialog(null, «Debe de ingresar un número entre 1 y 1000″,»¡Advertencia!»,JOptionPane.INFORMATION_MESSAGE);
caja1.requestFocus();
cadena = «0»;
}
//validar la caja vacia y que se inserten numeros
num2 = Integer.parseInt(cadena);
et2.setText(«00″+cadena);
if(num2 <= 0 || num2 =9 && num2 = 100){
et2.setText(«»+num2);
caja1.setText(«»);
}
}
if(e.getSource() == btn2){
//En cada IF se incremente el numero y se llama a la funcion timbrar
//Obtener valor de la etiqueta que muestra el numero en pantalla
num = Integer.parseInt(et2.getText());
//Si el valor es mayo o menor a 9 y mayo a 0
if(num <= 0 || num = 9 && num = 99){
num = num + 1;
et2.setText(«»+num);
timbrar();
}
}
if(e.getSource() == btn3){
timbrar();
}
}
public void timbrar(){
//String filename= getClass().getResource(«/mp3/BELL1.mp3»).toString();
String filename = «src/mp3/bell1.mp3»;
Timbre t = new Timbre(filename);
// t.play();
int N = 500;
double suma = 0.0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
suma+=Math.sin(i+j);
}
}
// System.out.println(suma);
t.close();
t = new Timbre(filename);
t.play();
}
public static void main(String arg[]){
Turnos mp = new Turnos();
System.out.println(new File (".").getAbsolutePath());
System.out.println(new File ("/").getAbsoluteFile());
mp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mp.setLocation(790, 10);
mp.setResizable(false);
}
}
Muchas gracias.
Le hice algunas modificaciones al código para no hacerlo tan largo y también comparto una url del link de la librería:
http://www.java2s.com/Code/Jar/j/Downloadjl10jar.htm
package reproductor;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
import javax.swing.*;
import java.awt.event.*;
public class Reproductor extends JFrame implements ActionListener {
private void btnElegirActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc=new JFileChooser();
int seleccion=fc.showOpenDialog(this);
if(seleccion==JFileChooser.APPROVE_OPTION){
File fichero=fc.getSelectedFile();
txtReproductor.setText(fichero.getAbsolutePath());
}
}
private void btnReproducirActionPerformed(java.awt.event.ActionEvent evt) {
//Creamos el FileInputStream con la ruta del fichero de audio
try(FileInputStream fis=new FileInputStream(txtReproductor.getText())){
//Creamos el objeto Player
Player player=new Player(fis);
//Reproducimos el fichero, una vez lo haga no podremos hacer nada hasta que termine
player.play();
}catch (JavaLayerException e1) {
JOptionPane.showMessageDialog(this, «No es un fichero de audio»);
}catch (IOException ex) {
Logger.getLogger(Reproductor.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Reproductor() {
getContentPane().setBackground(new java.awt.Color(255,255,0));
setLayout(null);
lblReproductor=new JLabel(«REPRODUCTOR MASTER-MUSIC:»);
lblReproductor.setBounds(20,8,200,30);
add(lblReproductor);
txtReproductor=new JTextField();
txtReproductor.setBounds(80,50,280,30);
add(txtReproductor);
btnElegir=new JButton(«Elegir»);
btnElegir.setBounds(120,120,100,30);
add(btnElegir);
btnElegir.addActionListener(this);
btnReproducir=new JButton(«Reproducir»);
btnReproducir.setBounds(230,120,100,30);
add(btnReproducir);
btnReproducir.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
btnReproducirActionPerformed(e);
btnElegirActionPerformed(e);
}
public static void main(String[] parametro) {
Reproductor consola=new Reproductor();
consola.setBounds(0,10,470,260);
consola.setVisible(true);
}
private JTextField txtReproductor;
private JButton btnElegir;
private JButton btnReproducir;
private JLabel lblReproductor;
}