Teach you easy to make Java music player _java

Source: Internet
Author: User
Tags abstract prefetch rand set time stub thread class

The realization principle of music player

Javase's multimedia function is very weak, so there is a special multimedia-processing plug-ins called JMF,JMF provides a model can be roughly divided into seven categories

* DataSource (data source)
* Interception equipment (Capture Device, including video and audio interception equipment)
* Viewer (Player)
* Processor (Processor)
* Data Pool (Datasink)
* Data formats (format)
* Manager (Manager)

And I did this music player Mymusicplayer (this is the class name I created) is just called the player class in JMF to achieve its playback and other functions.

The first thing we have to do is to install JMF. The installation of JMF, believed to be nerve-racking for many novices, JMF only supports 32-bit JDK versions, whereas an IDE environment like eclipse corresponds to the JDK, where the IDE environment supports 32-bit JDK versions. After the installation of JMF, sometimes for MP3 playback is not successful, but also need to install JMF mp3plugin.

Second, the interface effect diagram

Third, functional structure chart

Four, the various implementation function code

public class Mymusicplayer implements ActionListener, controllerlistener,runnable{JFrame j=new JFrame ("Music player");
  JLabel tableplaer=new JLabel ("Play List");
  JButton badd=new JButton ("Add song");
  JButton bdelect=new JButton ("delete song");

  JButton bdelecttable=new JButton ("Empty list");
  JButton bmovenext=new JButton ("next song");
  JButton bmoveprevious=new JButton ("Last Song");
  JButton bplayer=new JButton ("suspend");
  JButton bstop=new JButton ("Stop");
  JButton bset=new JButton ("show lyrics");
  JButton bend=new JButton ("Stop");               String[] s={"Sequential play", "single loop", "Random Play"};                   The Drop-down list option array JComboBox select=new JComboBox (s);                      Create a drop-down option JPanel p1=new JPanel (); 
  Play List area JPanel p=new JPanel ();                      JPanel p2=new JPanel (); 
  Button Area JPanel p3=new JPanel (); 
  JLabel l=new JLabel ();  JPanel p5=new JPanel ();  Place Playlist JPanel p6=new JPanel ();
  Place the name of the play song Static JPanel Pp=new JPanel ();
  static JLabel lb;


  public static JTextArea jt=new JTextArea (); Static int index;
  The subscript int count for the playlist;     int flag; Whether the tag is played randomly or sequentially int countsecond;
  Gets the total time value of the music static int newtime = 0; int ischanging = 0;  When the mouse is clicked on the cursor, the progress value also changes int ispressing = 0;
  Determine if the mouse clicks on the cursor File musicname = null;   static java.util.list<file> musicnames = null;
  Using generics, create the file object file CurrentDirectory = null; List list;//file listing FileDialog open;

  Define file Dialog Object Random rand = new Random ();


  String filename;
  progress bar JButton timeinformation = new JButton ();  JSlider Timeslider = new JSlider (swingconstants.horizontal, 0, 100, 0); (Swingconstants.horizontal) A set of constants (0, 100, 0) that are used to orient the progress bar to a horizontal direction, with the specified minimum, maximum, and initial values to create a


  A horizontal slider.  
  Play player player = null;


  Musicfilechooser filechooser = new Musicfilechooser ();   Static Jtextpane tp=new Jtextpane (); Show lyrics area static JTextArea are=new JTextArea ();
    Show picture Area 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);

    Sets the song P6.add (l) to display the playback;
    * * Implementation of the picture insert * * * * * * ImageIcon ic=new ImageIcon ("image\\2.3.jpg"); Ic=new ImageIcon (Ic.getimage (). getScaledInstance (880, 477, 2));
    Get picture and set picture size Lb=new JLabel (IC);     
    Lb.setopaque (FALSE);    Pp.setopaque (FALSE);


    Set to Transparent 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);
    File list = new list (10);  List.setbounds (100, 55, 187, 495);
    List Area 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 ("Song Body", 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); /* Implement the progress bar */timeslider.setmajortickspacing (1);//Call this method to set the interval of the primary tick mark.
     The number passed in represents the distance measured by value between each major tick mark.  Timeslider.setpaintticks (TRUE); 
To draw the master scale, Setpaintticks must be set to True Timeslider.addchangelistener (new ChangeListener () {///Create a new ChangeListener to add to the slider.       public void statechanged (ChangeEvent arg0) {if (player!= null && ispressing = 1) {n
           Ewtime = (int) (JSlider) Arg0.getsource ()). GetValue (); Timeinformation.settext ("Current Time:" +newtime/60+ ":" +newtime%60+ "| |"
           + "Total time:" +countsecond/60+ ":" +countsecond%60);
         ischanging = 1;
     }
       }
     }); Timeslider.addmouselistener (New Mouseadapter () {public void mousepressed (MouseEvent arg0) {ispressing = 1      ;      When the mouse clicks on the cursor} public void mousereleased (MouseEvent arg0) {ispressing = 0;
     When the mouse does not click on the cursor}});    Timeinformation.settext ("Current time: 00:00 | |
     Total time: 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);
  } * * Main function * */public static void main (string[] args) throws IOException, interruptedexception {//interruptedexception: When the thread is in the active
    Throws the exception Mymusicplayer Play=new Mymusicplayer () when the previous or active period is in the waiting, sleeping, or occupied state and the thread is interrupted.
    Thread timerun = new thread (play); 
  Timerun.start ();          @Override public void actionperformed (ActionEvent e) {String cmd = E.getactioncommand ();      To determine whether to play or pause by getting a string, string box= (String) Select.getselecteditem (); Determines the sequence of playback if (E.getsource () ==badd) {if (player = null) {if (Filechooser.showopendialog (j) = = Music Filechooser.approve_option) {this.
          Musicname = Filechooser.getselectedfile (); File cd = Filechooser.getcurrentdirectory ();  Gets the current path if (CD!= this.currentdirectory| | this.currentdirectory = = NULL) {filefilter[] Filefilters  = Filechooser.getchoosablefilefilters (); FileFilter is an abstract class that jfilechooser use to filter the collection of files displayed to the user, file files[] = Cd.listfiles (); Cd.listfiles () represents a array group that returns an abstract path,These path names represent the files in the directory represented by this abstract path name. This.
            Musicnames = new arraylist<file> (); for (file file:files) {//Each loop assigns the file object in the array to the variable, and then operates on the variable in the loop body as follows://for (int i=0;i<file
              s.length;i++) {file = Files[i];.}      filename = File.getname (). toLowerCase (); Get All Music names for (FileFilter filter:filefilters) {if (!file.isdirectory () && Filte R.accept (file)) {this.
                   Musicnames.add (file);
                  List.add (filename);
                Filename=e.getactioncommand ();  {}}} index = Musicnames.indexof (musicname);
          Define a song's Subscript count = Musicnames.size ();
        Playfile ();
      } else {Player.start ();
      } if (Cmd.equals ("paused")) {Bplayer.settext ("play");   
      Player.stop ();
      } if (Cmd.equals ("Play")) {Bplayer.settext ("paused");
    Player.start ();

}    if (E.getsource () ==bstop) {//stop if (player!= null) {player.stop ();   Timeinformation.settext ("Current time: 00:00 | |
          Total time: 00:00 ");
          Timeslider.setvalue (0);  Player.setmediatime (New Time (0)); Set time to Zero}} if (E.getsource () ==bmovenext) {//Next if (player!= null) {if ("sequential playback". Equals (
          box)) {Nextmusic (); if ("Random play". 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 (); If you click on the previous one, the current song will stop playing, play the previous try {Player=manager.createrealizedplayer (musicnames.get) (i
                    Ndex). Touri (). Tourl ());
                    Player.prefetch (); Player.setmediaTime (0.0);//start playing Player.addcontrollerlistener (this) from a certain period; L.settext ("Playing:" +this.)
                    Musicnames.get (Index). toString ());
                    List.select (index); 
                    Player.start ();
                  flag=1; catch (Noplayerexception | cannotrealizeexception |
                  IOException E1) {e1.printstacktrace ();
         if (E.getsource () ==bmoveprevious) {//previous if (player!= null) {
          if ("Sequential playback". Equals (Box)) {Previousmusic (); if ("Random 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;       } player.stop (); If you click on the previous one, the current song will stop playing, playPrevious try {Player=manager.createrealizedplayer (Musicnames.get (index). Touri (). Tourl ());
                Player.prefetch ();
                Player.setmediatime (New Time (0.0));//start playing Player.addcontrollerlistener (this) from a period; L.settext ("Playing:" +this.)
                Musicnames.get (Index). toString ());
                List.select (index); 
                Player.start ();
              flag=1; catch (Noplayerexception | cannotrealizeexception |
              IOException E1) {e1.printstacktrace (); }} if (E.getsource () ==bdelect) {//delete Song Index =list.getselectedindex (
      );
      List.remove (index);
    Musicnames.remove (This.index);
      } if (E.getsource () ==bdelecttable) {//Empty list list.removeall ();
      Musicnames.removeall (Musicnames);
      Player.stop ();
    Player = null; //When you double-click the list, implement play List.addmouselistener (new Mouseadapter () {PUBlic void mouseclicked (MouseEvent e) {//Double-click when processing if (e.getclickcount () = = 2) {if (player!=null) {
          Player.stop ();
          //Play the selected file Index=list.getselectedindex ();
        Playfile ();

}  
      }
    }); //Because the "Controllerlistener" interface is implemented, this method is used to handle events from the media Player; public void Controllerupdate (Controllerevent e) {String box=      (String) Select.getselecteditem ();
      Determines the sequence of playback if (e instanceof endofmediaevent) {player.setmediatime (new time (0));
      if ("Single loop". Equals (Box)) {Player.start ();
      if ("Sequential play". Equals (Box)) {Nextmusic (); if ("Random play". 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));//start playing Player.addcontrollerlistener (this) from a period; L.settext ("Playing:" +this.)
                Musicnames.get (Index). toString ());
                List.select (index); 
                Player.start ();
              flag=1; catch (Noplayerexception | cannotrealizeexception |
              IOException E1) {e1.printstacktrace (); /** * Get MP3 Song name * * @MP3 file path * @ Song name/public String Getmusicname (stri
    ng 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; 


  /** * The next implementation function */public void Nextmusic () {}/** * Previous implementation function * * public void Previousmusic () {} /** * Play MP3 file main function/public void Playfile () {try {player = Manager.createrealizedplayer (musicnames
      . Get (Index). Touri (). Tourl ()); Player.preFetch ();
      Player.setmediatime (New Time (0.0));//start playing Player.addcontrollerlistener (this) from a period;
      L.setfont (New Font ("Song Body", 0,20)); L.settext ("Playing:" +this.)  Musicnames.get (Index). toString ());
      Displays the song that is playing List.select (index);

      Player.start ();
      Mythread11 tt=new Mythread11 ();

    Tt.start ();
      catch (Exception E1) {//When a piece of music cannot be played, it is processed 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-generated Method Stub musicnames.remove (index);
  if (--count = = index) index = 0;
  if (count = = 0) player = null;
  else Playfile ();  /** * MP3 file Filter Internal class */class Musicfilechooser extends JFileChooser {}/** * MP3 file Filter Secondary Internal class * */Class Myfilefilter Extends FileFilter {//filefilter is an abstract class, JFileChooser Use it to filter the collection of files displayed to the user 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;
    }/** * Read Show time progress bar */public void run () {while (true) {sleep ();
          if (player!= null) {if (ispressing = 0) {if (ischanging = = 1) {newtime = Timeslider.getvalue ();
          Player.setmediatime (((long) newtime) *1000000000);
        ischanging = 0;
          else {newtime = (int) player.getmediatime (). getseconds ();
          Timeslider.setvalue (NewTime);   Timeinformation.settext ("Current Time:" +newtime/60+ ":" +newtime%60+ "| | "+" Total time: "+countsecond/60+ ":" +countsecond%60); The thread class Mythread11 extends thread {public void run () {//TODO auto-generated met 
      Hod stub 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 ("Arial
  ", 1,20));
  Tp.setforeground (Color.Blue);
  Styleddocument doc = Tp.getstyleddocument ();
  SimpleAttributeSet Center = new SimpleAttributeSet ();   Styleconstants.setalignment (center, Styleconstants.align_center);
  Displays doc.setparagraphattributes in the lyrics area (0, Doc.getlength (), center, false);
  Tp.settext ("Artist:" + Ls.getar ());
  Tp.settext ("album:" + Ls.getal ());
  Tp.settext ("Song:" + Ls.getti ());
  Tp.settext ("Lyric production:" + Ls.getby ());
    for (lyric l:ls.getlyrics ()) {Tp.settext (L.gettxt ());
  Thread.Sleep (L.gettimesize ());

 }
}

}

V. Overall test results

As follows

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.