English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Te enseño a hacer un reproductor de música java fácilmente

一、音乐播放器的实现原理

 Javase的多媒体功能很弱,所以有一个专门处理多媒体的插件叫JMF,JMF提供的模型可大致分为七类

* 数据源(Data source)
* 截取设备(Capture Device,包括视频和音频截取设备)
* 播放器(Player)
* 处理器(Processor)
* 数据池(DataSink)
* 数据格式(Format)
* 管理器(Manager)

而我所做的这个音乐播放器MyMusicPlayer(这是我创建的类名)正是调用了JMF中的Player类来实现其播放等各种功能.

我们首先要做的就是要安装JMF。JMF的安装,相信对于许多的新手来说是很伤脑筋的,JMF只支持32版本JDK,然而像eclipse这样的IDE环境要与JDK对应,也就是IDE环境要支持32版本JDK。安装完JMF之后,有时候对于MP3La reproducción no tiene éxito,还需要安装JMF的mp3plugin.

Dos,效果图 de la interfaz

Tres, diagrama de estructura de funciones

Cuatro, código de implementación de diversas funciones

public class MyMusicPlayer implements ActionListener, ControllerListener,Runnable{
 JFrame j = new JFrame("Reproductor de música");
 JLabel TablePlaer = new JLabel("Lista de reproducción");
 JButton BAdd = new JButton("Agregar canción");
 JButton BDelect = new JButton("Eliminar canción");
 JButton BDelectTable = new JButton("Limpiar lista");
 JButton BMoveNext = new JButton("Canción siguiente");
 JButton BMovePrevious = new JButton("Canción anterior");
 JButton BPlayer = new JButton("Pausar");
 JButton BStop = new JButton("Detener");
 JButton BSet = new JButton("Mostrar letras");
 JButton BEnd = new JButton("Detener");
 String[] s={"Reproducir en orden","Reproducción en bucle","Reproducción aleatoria"};        //Array de opciones de lista desplegable
 JComboBox select=new JComboBox(s);          //Crear opciones desplegables
 JPanel p1=new JPanel();           //Área de lista de reproducción
 JPanel p=new JPanel(); 
 JPanel p2=new JPanel();           //Área de botones
 JPanel p3=new JPanel(); 
 JLabel l=new JLabel(); 
 JPanel p5=new JPanel(); //Colocar la lista de reproducción
 JPanel p6=new JPanel(); //Colocar el nombre de la canción reproducida
 static JPanel pp=new JPanel();
 static JLabel lb;
 public static JTextArea jt=new JTextArea();
 static int index;  //Índice de la lista de reproducción
 int count;
 int flag;   //Marcar si es reproducción aleatoria o en orden
 int countSecond; //Obtener el valor total del tiempo de la música
 static int newtime = 0;
 int ischanging = 0; //Cuando el ratón hace clic en el cursor, también cambia el valor de la barra de progreso
 int ispressing = 0; //Determinar si el ratón hace clic en el cursor
 File MusicName = null;
 static java.util.List<File> MusicNames = null;  //Crear un objeto File utilizando generics
 File currentDirectory = null;
 List list;// 文件列表
 FileDialog open; // Definir el objeto de cuadro de diálogo de archivo
 Random rand = new Random();
 String filename;
 //Barra de progreso
 JButton timeInformation = new JButton();
 JSlider timeSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 100, 0); //Un conjunto de constantes (SwingConstants.HORIZONTAL) utilizadas para orientar la barra de progreso en dirección horizontal.
                     //( 0, 10Crear un deslizador horizontal con valores mínimo, máximo e inicial especificados en (0, 0).
 // Reproducir
 Player player = null; 
 MusicFileChooser fileChooser = new MusicFileChooser();
 static JTextPane tp=new JTextPane();  //Mostrar la región de las letras
 static JTextArea are=new JTextArea(); //Mostrar la región de la imagen
 public MyMusicPlayer(){
  j.setSize(1200, 700);
  j.setLayout(null);
  j.getContentPane().setBackground(Color.BLACK);
  j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  p.setBounds(2, 563, 1180, 95);
  p.setLayout(new BorderLayout());
  p1.setBounds(2, 3, 298, 30);   
  p1.setBackground(new Color(255,255,255));
  p2.setLayout(new GridLayout(2,3,20,20));
  p2.setBackground(Color.LIGHT_GRAY);
  p3.setLayout(new GridLayout(2,0,200,10));
  p3.setBackground(new Color(255,255,255));
  p5.setBounds(2, 35, 298, 526);
  p5.setLayout(null);
  p5.setBackground(new Color(255,255,255));
  p6.setBounds(301, 3,880, 30);
  p6.setLayout(null);
  p6.setBackground(new Color(255,255,255));
  l.setBounds(250, 4, 600, 30);  //Establecer la reproducción de la canción
  p6.add(l);
  /*Implementar la inserción de imágenes
   * */
  ImageIcon ic=new ImageIcon("image\\2.3.jpg");
  ic=new ImageIcon(ic.getImage().getScaledInstance(880, 477, 2)); //Obtener la imagen y establecer el tamaño de la imagen
  lb=new JLabel(ic);
  lb.setOpaque(false);   
  pp.setOpaque(false);  //Establecer a transparente
  pp.setBounds(241, 80,990, 500);
  are.setBounds(241, 56,990, 520);
  are.setOpaque(false);
  tp.setBackground(new Color(255,255,255));
  tp.setBounds(301, 35,880, 49);
  pp.add(are);
  pp.add(lb);
  // 文件列表
  list = new List(10);
  list.setBounds(100, 55, 187, 495); //区域列表
  list.addActionListener(this);
  j.add(list);
  j.add(jt);
  j.add(tp);
  BAdd.setBounds(5,20, 90,30);
  BAdd.setBackground(new Color(255,255,255));
  BDelect.setBounds(5, 80, 90, 30);
  BDelect.setBackground(new Color(255,255,255));
  BDelectTable.setBounds(5, 140, 90, 30);
  BDelectTable.setBackground(new Color(255,255,255));
  TablePlaer.setBounds(30, 100, 200, 50);
  TablePlaer.setFont(new Font("宋体",1, 20));
  p1.add(TablePlaer);
  BMovePrevious.setBackground(new Color(255,255,255));
  BPlayer.setBackground(new Color(255,255,255));
  BMoveNext.setBackground(new Color(255,255,255));
  BStop.setBackground(new Color(255,255,255));
  select.setBackground(new Color(255,255,255));
  BSet.setBackground(new Color(255,255,255));
  p2.add(BMovePrevious);
  p2.add(BPlayer);
  p2.add(BMoveNext);
  p2.add(BStop);
  p2.add(select);
  p2.add(BSet);
  p2.setBackground(new Color(255,255,255));
  p.add(p2,BorderLayout.WEST);
  p.add(p3,BorderLayout.CENTER);
  p5.add(p);
  p5.add(BAdd);
  p5.add(BDelect);
  p5.add(BDelectTable);
  BAdd.addActionListener(this);
  BDelect.addActionListener(this);
  BDelectTable.addActionListener(this);
  BMoveNext.addActionListener(this);
  BPlayer.addActionListener(this);
  BMovePrevious.addActionListener(this);
  BStop.addActionListener(this);
  select.addActionListener(this);
  BSet.addActionListener(this);
  timeInformation.setEnabled(false);
   /*
   * 实现进度条
   * */ 
   timeSlider.setMajorTickSpacing(1);//Llame a este método para establecer el intervalo de las marcas principales. El número传入 representa la distancia medida en valores entre cada marca principal.
   timeSlider.setPaintTicks(true); //Para dibujar las marcas principales, setPaintTicks debe establecerse en true
   timeSlider.addChangeListener(new ChangeListener() { //Crear un nuevo ChangeListener y agregarlo al control deslizante.
    public void stateChanged(ChangeEvent arg0) {
     if (player != null && ispressing == 1) {
      newtime = (int)((JSlider)arg0.getSource()).getValue();
      timeInformation.setText("Tiempo actual:");+newtime/60+":"+newtime%60+"  ||  "+" Tiempo total: "+countSecond/60+":"+countSecond%60);
      ischanging = 1;
     }
    }
   });
   timeSlider.addMouseListener(new MouseAdapter(){
    public void mousePressed(MouseEvent arg0) {
     ispressing = 1;   //Cuando el ratón hace clic en el cursor
    }
    public void mouseReleased(MouseEvent arg0) {
     ispressing = 0;   //Cuando el ratón no hace clic en el cursor
    }
   });
   timeInformation.setText("Tiempo actual: 00:00  ||  Tiempo total: 00:00");
   timeInformation.setBackground(new Color(255,255,255));
   p3.add(timeInformation,BorderLayout.NORTH);
   p3.add(timeSlider,BorderLayout.SOUTH);
   j.add(pp);
   j.add(p5);
   j.add(p);
   j.add(p1);
   j.add(p6);
   j.setVisible(true);
//  j.setResizable(false);
 }
 /*
  * Función principal
  * */
 public static void main(String[] args) throws IOException, InterruptedException { //InterruptedException: Se lanza esta excepción cuando un hilo está en estado de espera, sueño o ocupado antes o durante su actividad y el hilo es interrumpido
  MyMusicPlayer play=new MyMusicPlayer();
  Thread timeRun = new Thread(play);
  timeRun.start(); 
 }
 @Override
 public void actionPerformed(ActionEvent e) {
  String cmd = e.getActionCommand();     //A través de la obtención de la cadena para determinar si se reproducirá o pausará
  String box=(String)select.getSelectedItem();   //Determinar el orden de reproducción
  if(e.getSource()==BAdd)
  {
   if (player == null) {
    if (fileChooser.showOpenDialog(j) == MusicFileChooser.APPROVE_OPTION) {
     this.MusicName = fileChooser.getSelectedFile();
     File cd = fileChooser.getCurrentDirectory(); //Obtener la ruta actual
     if (cd != this.currentDirectory || this.currentDirectory == null) {
      FileFilter[] fileFilters = fileChooser.getChoosableFileFilters(); //FileFilter es una clase abstracta, JFileChooser lo utiliza para filtrar la colección de archivos mostrada al usuario
      File files[] = cd.listFiles(); //cd.listFiles() representa un array de nombres de rutas abstractas, que representan los archivos en el directorio que representa esta ruta abstracta.
      this.MusicNames = new ArrayList<File>();
      for (File file : files) { //Cada vez que se ejecute el bucle, se asigna el objeto archivo del array al variable file, y luego se realiza una operación sobre esta variable en el cuerpo del bucle, como:
             //for(int i=0;i<files.length;i++{ file = files[i];……}
       filename = file.getName().toLowerCase();   //Obtener todos los nombres de música
       for (FileFilter filter : fileFilters) {
        if (!file.isDirectory() && filter.accept(file)) {
         this.MusicNames.add(file);
          list.add(filename);
         filename=e.getActionCommand();
        }
       }
      }
     }
     index = MusicNames.indexOf(MusicName); //definir el índice de la canción
     count = MusicNames.size();
     PlayFile();
    }
   } else {
    player.start();
   }
  }
  if(cmd.equals("pausar")){
   BPlayer.setText("reproducir");
   player.stop();  
   }
  if(cmd.equals("reproducir")){
   BPlayer.setText("pausar");
   player.start();
  }
  if(e.getSource()==BStop){   //detener
    if (player != null) {
     player.stop();
     timeInformation.setText("Tiempo actual:00:00  ||  Tiempo total:00:00");
     timeSlider.setValue(0);
     player.setMediaTime(new Time(0)); //se establece el tiempo a cero
  }
    }
  if(e.getSource()==BMoveNext){  //siguiente canción
    if (player != null) {
     if("ReproducciónSecuencial".equals(box)){
      nextMusic();
     }
     if("ReproducciónAleatoria".equals(box)){
      int index = (int) rand.nextInt(this.MusicNames.size())+1;
       if (this.MusicNames != null && !this.MusicNames.isEmpty()) {
         if ( ++index == this.MusicNames.size()) {
          index=(int) rand.nextInt(this.MusicNames.size())+1;
         }
         player.stop();   //si se hace clic en la canción anterior, se detiene la reproducción de la canción actual y se reproduce la canción anterior
         try {
          player=Manager.createRealizedPlayer(MusicNames.get(index).toURI().toURL());
          player.prefetch();
          player.setMediaTime(new Time(0.0));// Reproducir desde un tiempo específico
          player.addControllerListener(this);
          l.setText("Reproduciendo: ",+this.MusicNames.get(index).toString());
          list.select(index);
          player.start(); 
          flag=1;
         } catch (NoPlayerException | CannotRealizeException | IOException e1) {
          e1.printStackTrace();
         }
       }
     }
    }
  }
  if(e.getSource()==BMovePrevious){  //canción anterior
    if (player != null) {
     if("ReproducciónSecuencial".equals(box)){
      PreviousMusic();
     }
     if("ReproducciónAleatoria".equals(box)){
      int index = (int) rand.nextInt(this.MusicNames.size())+1;
      if (this.MusicNames != null && !this.MusicNames.isEmpty()) {
       if ( index--==(int) rand.nextInt(this.MusicNames.size())+1) {
        index = this.MusicNames.size() - 1;
       }
       player.stop();    //si se hace clic en la canción anterior, se detiene la reproducción de la canción actual y se reproduce la canción anterior
       try {
        player=Manager.createRealizedPlayer(MusicNames.get(index).toURI().toURL());
        player.prefetch();
        player.setMediaTime(new Time(0.0));// Reproducir desde un tiempo específico
        player.addControllerListener(this);
        l.setText("Reproduciendo: ",+this.MusicNames.get(index).toString());
        list.select(index);
        player.start(); 
        flag=1;
       } catch (NoPlayerException | CannotRealizeException | IOException e1) {
        e1.printStackTrace();
       }
      }
    }
    }
  }
  if(e.getSource()==BDelect){    //se elimina la canción
   index = list.getSelectedIndex();
   list.remove(index);
   MusicNames.remove(this.index);
  }
  if(e.getSource()==BDelectTable){   //se vacía la lista
   list.removeAll();
   MusicNames.removeAll(MusicNames);
   player.stop();
   player = null;
  }
  //al hacer doble clic en la lista se realiza la reproducción
  list.addMouseListener(new MouseAdapter() {
   public void mouseClicked(MouseEvent e) {
    // al hacer doble clic se procesa
    if (e.getClickCount() == 2) {
     if(player!=null){
      player.stop();
     }
     // Reproducir el archivo seleccionado
     index=list.getSelectedIndex();
     PlayFile();
    } 
   }
  });
}
 // Debido a que se ha implementado el interfaz "ControllerListener", este método se utiliza para manejar los eventos enviados por el reproductor de medios;
 public void controllerUpdate(ControllerEvent e) {
  String box=(String)select.getSelectedItem();   //Determinar el orden de reproducción
  if (e instanceof EndOfMediaEvent) {
   player.setMediaTime(new Time(0));
   if ("ReproducciónEnCiclo".equals(box)) {
    player.start();
   }
   if("ReproducciónSecuencial".equals(box)){
    nextMusic();
   }
   if("ReproducciónAleatoria".equals(box)){
     if (this.MusicNames != null && !this.MusicNames.isEmpty()) {
       int index = (int) rand.nextInt(this.MusicNames.size())+1;
       try {
        player=Manager.createRealizedPlayer(MusicNames.get(index).toURI().toURL());
        player.prefetch();
        player.setMediaTime(new Time(0.0));// Reproducir desde un tiempo específico
        player.addControllerListener(this);
        l.setText("Reproduciendo: ",+this.MusicNames.get(index).toString());
        list.select(index);
        player.start(); 
        flag=1;
       } catch (NoPlayerException | CannotRealizeException | IOException e1) {
        e1.printStackTrace();
       }
     }
   }
  }
 }
  /**
  * ObtenerMP3NombreDeLaCanción
  * 
  * @MP3rutaDeArchivo
  * @NombreDeLaCanción
  */
 public String getMusicName(String str) {
  int i;
  for (i = str.length() - 1; i > 0; i--) {
   if (str.charAt(i) == '\\')
    break;
  }
  str = str.substring(i + 1, str.length() - 4);
  return str;
 }
 /**
  * la función de reproducción del siguiente tema
  */
 public void nextMusic() {
 }
 /**
  * la función de reproducción del anterior tema
  */
 public void PreviousMusic() {
 }
 /**
  * Reproducir MP3Función principal del archivo
  */
 public void PlayFile() {
  try {
   player = Manager.createRealizedPlayer(MusicNames.get(index).toURI().toURL());
   player.prefetch();
   player.setMediaTime(new Time(0.0));// Reproducir desde un tiempo específico
   player.addControllerListener(this);
   l.setFont(new Font("宋体",0,20));
   l.setText("Reproduciendo: ",+this.MusicNames.get(index).toString()); //Mostrar la canción que se está reproduciendo
   list.select(index);
   player.start();
   Mythread11 tt=new Mythread11();
   tt.start();
  } catch (Exception e1) { //Cuando se detecta una canción que no puede reproducirse, procede a manejarla
   dealError();
   return;
  }
  this.setFrame();
  }
 public void setFrame()
 {
  countSecond = (int)player.getDuration().getSeconds();
  timeSlider.setMaximum(countSecond);
  timeSlider.setValue(0);
  newtime = 0;
 }
private void dealError() {  
  // TODO Auto-metodo de plantilla generado
 MusicNames.remove(index);
 if( --count == index )
  index = 0;
 if( count == 0)
  player = null;
 else
  PlayFile();
 }
/**
 * MP3Clase interna de filtrado de archivos
 */
class MusicFileChooser extends JFileChooser {
 }
/**
 * MP3Clase auxiliar de filtrado de archivos
 * 
 */
class MyFileFilter extends FileFilter { //FileFilter es una clase abstracta, JFileChooser lo utiliza para filtrar la colección de archivos mostrada al usuario
 String[] suffarr;
 String decription;
 public MyFileFilter() {
  super();
 }
 public MyFileFilter(String[] suffarr, String decription) {
  super();
  this.suffarr = suffarr;
  this.decription = decription;
 }
 public boolean accept(File f) {
  for (String s : suffarr) {
   if (f.getName().toUpperCase().endsWith(s)) {
    return true;
   }
  }
  return f.isDirectory();
 }
 public String getDescription() {
  return this.decription;
 }
}
/**
 * leer y mostrar la barra de progreso de tiempo
 */
public void run() {
 while(true) {
  sleep();
  if(player != null) {
   if(ispressing == 0) {
    if(ischanging == 1) {
     newtime = timeSlider.getValue();
     player.setMediaTime(new Time(((long)newtime)*1000000000));
     ischanging = 0;
    } else {
     newtime = (int)player.getMediaTime().getSeconds();
     timeSlider.setValue(newtime);
     timeInformation.setText("Tiempo actual: "+newtime/60+":"+newtime%60+"  ||  "+"Tiempo total: "+countSecond/60+":"+countSecond%60);
    }
   }
  }
 }
}
//implementar la hebra de letras
class Mythread11 extends Thread { 
 public void run() {
  // TODO Auto-metodo de plantilla generado
  try{
   LRC lrc = ReadLRC.readLRC("Traveling Light.lrc"); 
   Lyrics ls = ParseLRC.parseLRC(lrc); 
   playTest(ls);}}
  }catch(Exception e){
  }
 }
}
static void playTest(Lyrics ls) throws InterruptedException {
 tp.setFont(new Font("宋体",1,20));
 tp.setForeground(Color.BLUE);
 StyledDocument doc = tp.getStyledDocument();
 SimpleAttributeSet center = new SimpleAttributeSet();
 StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);  //Mostrar en la zona de letras
 doc.setParagraphAttributes(0, doc.getLength(), center, false);
 tp.setText("Artista: "); + ls.getAr());
 tp.setText("Álbum: "); + ls.getAl());
 tp.setText("Canción: "); + ls.getTi());
 tp.setText("Creación de letras: "); + ls.getBy());
 for (Lyric l : ls.getLyrics()) {
  tp.setText(l.getTxt());
  Thread.sleep(l.getTimeSize());
 }
}
}

V. Efecto de prueba general

Como se muestra

Para obtener más información sobre los reproductores, haga clic en 'Funciones del reproductor java' para aprender.

Este es el contenido completo del artículo, espero que sea útil para su aprendizaje y que apoyen más al tutorial de gritos.

Te gustará