1. El principio de implementación del reproductor de música
La función multimedia de Javase es muy débil, por lo que hay un complemento que se especializa en multimedia llamado JMF. Los modelos proporcionados por JMF se pueden dividir aproximadamente en siete categorías.
* Fuente de datos
* Dispositivo de captura (incluido el interceptor de video e audio)
* Jugador
* Procesador
* Enlace de datos
* Formato de datos (formato)
* Gerente
El reproductor de música MyMusicPlayer (este es el nombre de clase que creé) hice llamadas a la clase de reproductor en JMF para implementar varias funciones, como su reproducción.
Lo primero que tenemos que hacer es instalar JMF. Creo que la instalación de JMF es muy problemática para muchos novatos. JMF solo admite la versión JDK de 32 bits, pero los entornos IDE como Eclipse deben corresponder a JDK, es decir, el entorno IDE debe admitir la versión JDK de 32 bits. Después de instalar JMF, a veces la reproducción de MP3 no tiene éxito, y también necesita instalar MP3Plugin de JMF.
2. Diagrama de efecto de interfaz
3. Diagrama de estructura funcional
4. Varios códigos para implementar funciones
clase pública MyMusicPlayer implementa ActionListener, ControllerListener, Runnable {jframe j = new Jframe ("Music Player"); Jlabel tablePlaer = new JLabel ("Lista de reproducción"); JButton Badd = nuevo JButton ("Agregar canción"); JButton bdelect = new JButton ("Song Song"); JButton bdelectTable = new JButton ("Lista clara"); JButton BMoVENEXT = new JButton ("Siguiente canción"); JButton BmovePrevious = new JButton ("Song anterior"); JButton bplayer = new JButton ("Pausa"); JButton bstop = new JButton ("Stop"); JButton bset = new JButton ("Show Lyrics"); JButton Bend = new JButton ("Stop"); String [] s = {"Securial Play", "Single Loop", "Shutter Play"}; // opción de desplegable Array 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 botón JPanel P3 = new JPanel (); Jlabel l = new JLabel (); Jpanel p5 = new JPanel (); // Lista de reproducción JPanel p6 = new JPanel (); // Coloque el nombre de la canción Song Static Jpanel pp = new JPanel (); Jlabel estático LB; public static jTextArea JT = new JTextArea (); Índice de int static int; // subíndice de la lista de reproducción int count; int flag; // es el marcador de la lista de reproducción que juega al azar o secuencialmente en int countsecond; // Obtener el valor de tiempo total de la música static int newtime = 0; int ischanging = 0; // Cuando el mouse hace clic en el cursor, el valor de progreso también cambiará int ispressing = 0; // defender si el mouse hace clic en el archivo cursor musicname = null; static java.util.list <Sche> MusicNames = null; // Use genéricos para crear archivo de objeto de archivo thurndirectory = null; Lista de lista; // Lista de archivos FileDialog abrir; // Definir el objeto de diálogo Archivo Rand Rand = new Random (); Nombre de archivo de cadena; // Progress Bar JButton TimeInformation = new JButton (); JSLider TimesLider = new JSlider (SwingConstants.Horizontal, 0, 100, 0); //(SwingConstants.horizontal) se usa para dirigir el conjunto de constantes con la barra de progreso como dirección horizontal // (0, 100, 0) crea un deslizador horizontal con los valores mínimos, máximos y iniciales especificados. // Play Player Player = Null; MusicFilECHOOSER FILECHOOSER = new MusicFilECHOOSER (); static jTextPane tp = new JTextPane (); // Mostrar área lírica estática JTextArea son = new JTexTarea (); // Mostrar área de imagen public myMusicPlayer () {J.Setsize (1200, 700); J.SetLayout (NULL); J.GetContentPane (). Sucedingground (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 (nuevo color (255, 255, 255)); P2.SetLayout (nuevo GridLayout (2, 3, 20, 20)); P2.SetBackground (color.light_gray); p3.setLayout (nuevo GridLayout (2,0,200,10)); P3.SetBackground (nuevo color (255,255,255)); p5.setBounds (2, 35, 298, 526); P5.SetLayout (NULL); P5.SetBackground (nuevo color (255,255,255)); p6.setBounds (301, 3,880, 30); p6.setLayout (nulo); P6.SetBackground (nuevo color (255,255,255)); L.SetBounds (250, 4, 600, 30); // Establecer la canción P6.Add (l) mostrada y reproducida; /*Implementar inserción de imagen**/imageiCon ic = new Imageicon ("Imagen // 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 (falso); pp.SetOpaque (falso); // establecido en transparente pp.setBounds (241, 80,990, 500); are.setBounds (241, 56,990, 520); son.setOpaque (falso); TP.SetBackground (nuevo color (255,255,255)); TP.SetBounds (301, 35,880, 49); pp.add (are); pp.add (lb); // Lista de archivos = nueva lista (10); list.setBounds (100, 55, 187, 495); // Lista de área list.addactionListener (esto); J.Add (lista); J.Add (JT); J.Add (TP); Badd.setBounds (5,20, 90,30); Badd.setbackground (nuevo color (255,255,255)); Bdelect.setBounds (5, 80, 90, 30); Bdelect.setBackground (nuevo color (255,255,255)); Bdelect.setBounds (5, 140, 90, 30); Bdelect.setBackground (nuevo color (255,255,255)); TablePlaer.setBounds (30, 100, 200, 50); TablePlaer.setFont (nueva fuente ("安安", 1, 20)); p1.add (tablePlaer); Bmoveprevious.setbackground (nuevo color (255,255,255)); Bplayer.setbackground (nuevo color (255,255,255)); Bmovenext.setbackground (nuevo color (255,255,255)); Bstop.setbackground (nuevo color (255,255,255)); select.setbackground (nuevo color (255,255,255)); Bset.setbackground (nuevo color (255,255,255)); P2.Add (bmoveprevious); P2.Add (bplayer); P2.Add (Bmovenext); P2.Add (Bstop); p2.add (seleccionar); p2.add (bset); P2.SetBackground (nuevo 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 (esto); Bdelect.addactionListener (esto); Bdelecttable.addactionListener (this); Bmovenext.addactionListener (this); Bplayer.addactionListener (this); BMovePrevious.AddactionListener (esto); Bstop.addactionListener (this); select.AddactionListener (esto); Bset.addactionListener (this); TimeInformation.SetEnabled (falso); / * * Barra de progreso de implementación * */TimesLider.SetMajortickSpacing (1); // Llame a este método para establecer el intervalo de la marca de escala principal. El número entrante representa la distancia medida por valor entre cada marcador de escala principal. TimesLider.SetPaintTicks (verdadero); // Para dibujar la escala principal, SetPaintTicks debe establecerse en True TimesLider.AddChangeListener (new ChangeListener () {// Cree un nuevo ChangeListener y agregarlo al control deslizante. Public void statechanged (ChangeEvent Arg0) {if (Player! = Null && IsPressing == 1) {Newtime = (int) ((jslider) arg0.getSource ()). getValue (); TimesLider.AddMouseListener (new Mouseadapter () {public void Mousepressed (MouseEvent Arg0) {isPressing = 1; // cuando el mouse hace clic en el cursor} public void Mousereleded (mouseeVentEvent Arg0) {ispressing = 0; // cuando el ratón no hace clic en el cursor}}); TimeInformation.setText ("Hora actual: 00:00 || Tiempo total: 00:00"); TimeInformation.SetBackground (nuevo 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 (verdadero); // J.SetResizable (falso); } / * * Función principal * * /public static void main (string [] args) lanza ioexception, interruptedException {// interruptedException: cuando el hilo está en un estado de espera, durmiendo u ocupado antes o durante la actividad y el hilo se interrumpe, se lanza la excepción. MyMusicPlayer Play = new MyMusicPlayer (); Thread timerun = new Thread (Play); timerun.start (); } @Override public void ActionPerformed (ActionEvent E) {String cmd = e.getActionCommand (); // juzga si jugar o pausar obteniendo la cadena, string box = (string) select.getSelectedItem (); // juzga el orden de reproducción if (e.getSource () == Badd) {if (Player == NULL) {if (FILECHOOSER.ShowOpendialog (j) == MusicFilecooser.Approve_option) {this.musicName = fileChooser.getSelectedFile (); Archivo cd = fileCooser.getCurrentDirectory (); // Obtenga la ruta actual if (CD! = This.CurrentDirectory || this.CurrentDirectory == null) {fileFilter [] fileFilters = fileChooser.getChoosableFileFilters (); // FileFilter es una clase abstracta, que Jfilechooser usa para filtrar el conjunto de archivos que se muestran en los archivos de archivos de usuario [] = CD.ListFiles (); //cd.listfiles () significa devolver una matriz de nombres de ruta abstractos, que representan archivos en el directorio representado por este nombre de ruta abstracto. this.musicNames = new ArrayList <Sche> (); para (archivo de archivo: archivos) {// Cada vez que el objeto de archivo en la matriz se asigna a la variable de archivo, y luego esta variable se opera en el cuerpo de bucle, como: // for (int i = 0; i <files.length; i ++) {file = files [i]; ...} filename.getName (). tolowercase (); // Obtenga todos los nombres de música para (Filter Filter Filter: FileFilters) {if (! File.isDirectory () && Filter.accept (file)) {this.musicnames.add (file); list.add (nombre de archivo); FileName = e.getActionCommand (); }}}}} index = MusicNames.IndexOf (MusicName); // Definir el subíndice del recuento de canciones = musicnames.size (); Playfile (); }} else {Player.Start (); }} if (cmd.equals ("pausa")) {bplayer.setText ("play"); jugador.stop (); } if (cmd.equals ("play")) {bplayer.setText ("pausa"); Player.Start (); } if (e.getSource () == bstop) {// stop if (jugador! = null) {jugador.stop (); TimeInformation.setText ("Tiempo actual: 00: 00 || Tiempo total: 00: 00"); TimesLider.SetValue (0); jugador.setMediatime (nuevo tiempo (0)); // Establecer el tiempo en cero}} if (e.getSource () == BMoVENEXT) {// SIGUIENTE CANCIÓN if (Player! = NULL) {if ("Reproducción de secuencia" .equals (box)) {nextMusic (); } if ("Reproducción de obturador" .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; } jugador.stop (); // Si hace clic en la canción anterior, la canción actual se detendrá y la canción anterior se reproducirá Try {Player = Manager.CreateralizedPlayer (MusicNames.get (index) .touri (). Tourl ()); jugador.prefetch (); Player.setMediatime (nuevo tiempo (0.0)); // Player Player.AddControllerListener (esto); L.Settext ("Playing:"+this.MusicNames.get (index) .ToString ()); list.select (índice); Player.Start (); bandera = 1; } Catch (noplayerException | Can'tRealizeException | ioexception e1) {e1.printstackTrace (); }}}}}} if (e.getSource () == BMovePrevious) {// canción anterior if (Player! = Null) {if ("Play secuencial" .Equals (Box)) {AnteriorMusic (); } if ("shutter play" .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; } jugador.stop (); // Si hace clic en la canción anterior, la canción actual se detendrá y la canción anterior se reproducirá Try {Player = Manager.CreateralizedPlayer (MusicNames.get (index) .touri (). Tourl ()); jugador.prefetch (); jugador.setMediatime (nuevo tiempo (0.0)); // comienza a jugar jugador.addControllerListener (esto); L.Settext ("Playing:"+this.MusicNames.get (index) .ToString ()); list.select (índice); Player.Start (); bandera = 1; } Catch (noplayerException | Can'tRealizeException | ioexception e1) {e1.printstackTrace (); }}}}}}} if (e.getSource () == bdelect) {// delete Song index = list.getSelectedIndex (); list.remove (índice); MusicNames.remove (this.index); } if (e.getSource () == bdelecttable) {// Borrar la lista list.removeAll (); MusicNames.removeAll (MusicNames); jugador.stop (); jugador = nulo; } // Haga doble clic en la lista que se reproducirá list.AddMouseListener (new Mouseadapter () {public void MouseClicked (MouseEvent e) {// doble click if (e.getClickCount () == 2) {if (Player! = Null) {Player.Stop ();} // Play el archivo seleccionado = list.getEnectedDex (););); });} // Debido a que se implementa la interfaz "ControlerListener", este método se utiliza para manejar los eventos transmitidos desde el reproductor multimedia; public void controlerUpdate (controlervent e) {string box = (string) select.getSelectedItem (); // juzga la orden de reproducción if (e instancia de endofmediaevent) {jugador.setMediatime (New Time (0)); if ("Single Loop" .Equals (Box)) {Player.Start (); } if ("Play secuencial" .equals (box)) {nextMusic (); } if ("Shutter Play" .Equals (Box)) {if (this.MusicNames! = NULL &&! this.MusicNames.isEmpty ()) {int index = (int) rand.nextInt (this.musicNames.size ())+1; Pruebe {Player = Manager.CreateralizedPlayer (MusicNames.get (index) .Touri (). Tourl ()); jugador.prefetch (); Player.setMediatime (nuevo tiempo (0.0)); // Player Player.AddControllerListener (esto); L.Settext ("Playing:"+this.MusicNames.get (index) .ToString ()); list.select (índice); Player.Start (); bandera = 1; } Catch (noplayerException | Can'tRealizeException | ioexception e1) {e1.printstackTrace (); }}}}}} Ial for (i = str.length ()-1; i> 0; i--) {if (str.charat (i) == '//') break; } str = str.substring (i + 1, str.length () - 4); regresar str; } / *** Función de implementación Next* / public void nextMusic () {} / *** Función de implementación anterior* / public void anteriorMusic () {} / *** Reproducir la función principal de archivos mp3* / public void PlayFile () {try {Player = manager.createralizedPlayer (musicNames.get (index) .Touri (). TourL ()); jugador.prefetch (); Player.setMediatime (nuevo tiempo (0.0)); // Player Player.AddControllerListener (esto); L.SetFont (nueva fuente ("宋体", 0,20)); L.Settext ("Playing:"+this.MusicNames.get (index) .ToString ()); // Mostrar la canción que se reproduce list.select (índice); Player.Start (); MyThread11 tt = new MyThread11 (); tt.start (); } catch (Exception e1) {// Cuando no se puede reproducir una música, manejarla trastError (); devolver; } this.setFrame (); } public void setframe () {CountSecond = (int) Player.getDuration (). GetSeconds (); TimesLider.SetMaximum (CountSeCond); TimesLider.SetValue (0); Newtime = 0; } private void trastError () {// TODO Auto Generado Método STUB MusicNames.remove (índice); if (--count == index) index = 0; if (count == 0) jugador = nulo; else PlayFile (); }/*** Filtro interno de filtración de archivos mp3*/class MusicFilECHOOSer extiende jfilechooser {}/*** Filtrado de archivos mp3 de archivo Auxiliary**/class myfileFilter extiende FileFilter {// fileFilter es una clase abstracta, que Jfilechooser usa para filtrar la colección de archivos que se muestra a la cadena de usuarios [] sufarr; Descripción de la cadena; public myFileFilter () {super (); } public myFileFilter (String [] Suffarr, String Descripción) {super (); this.suffarr = Suffarr; this.descript = Descripción; } public boolean Acept (archivo f) {for (String S: Suffarr) {if (f.getName (). toUpperCase (). Endswith (s)) {return true; }} return f.isDirectory (); } public String getDescription () {return this.dection; }}/*** Leer la barra de progreso de tiempo de visualización*/public void run () {while (true) {sleep (); if (jugador! = null) {if (isPressing == 0) {if (ischanging == 1) {newtime = TimesLider.getValue (); jugador.setMediatime (nuevo tiempo (((largo) nuevo tiempo nuevo)*1000000000)); ischanging = 0; } else {newtime = (int) jugador.getMediatime (). getSeconds (); TimesLider.SetValue (Newtime); TimeInformation.setText ("Tiempo actual:"+Newtime/60+":"+Newtime%60+"||"+"Total Time:"+CountSeCond/60+":"+CountSecond%60); }}}}}}}}} // hilo que implementa letras myThread11 extiende hilo {public void run () {// tODO Auto Generated Stub intent {lrc lrc = readlrc.Readlrc ("Travelling.lrc"); Letras ls = parselrc.parselrc (lrc); Playtest (LS); } catch (excepción e) {}}} static void playtest (letra ls) lanza interruptedException {tp.setFont (nueva fuente ("宋体", 1,20)); tp.setForeground (color.blue); StyledDocument doc = tp.getStyledDocument (); SimpleatTributeset Center = new simpleatTributeset (); Styleconstants.setalignment (centro, styleconstants.align_center); // show doc.setparagraphattributes (0, doc.getLength (), centro, falso); tp.settext ("Artista:" + ls.getar ()); tp.settext ("Álbum:" + ls.getal ()); tp.settext ("Canción:" + ls.getti ()); tp.settext ("Producción de letras:" + ls.getby ()); para (lyric l: ls.getlyrics ()) {tp.setText (l.gettxt ()); Thread.sleep (l.gettimesize ()); }}}V. Resultados generales de la prueba
como sigue
Para obtener más información sobre el jugador, haga clic en "Función Java Player" para aprender.
Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.