1. O princípio da implementação do music player
A função multimídia da Javase é muito fraca, portanto, há um plug-in especializado em multimídia chamado JMF. Os modelos fornecidos pelo JMF podem ser divididos aproximadamente em sete categorias.
* Fonte de dados
* Capture Dispositivo (incluindo interceptador de vídeo e áudio)
* Jogador
* Processador
* DataSink
* Formato de dados (formato)
* Gerente
O Music Player MyMusicPlayer (este é o nome da classe que eu criei) que fiz chamadas para a classe de jogadores no JMF para implementar várias funções, como sua reprodução.
A primeira coisa que precisamos fazer é instalar o JMF. Acredito que a instalação do JMF é muito problemática para muitos novatos. O JMF suporta apenas a versão JDK de 32 bits, mas ambientes IDE como o Eclipse devem corresponder ao JDK, ou seja, o ambiente IDE deve suportar a versão JDK de 32 bits. Depois de instalar o JMF, às vezes a reprodução do MP3 não é bem -sucedida e você também precisa instalar o MP3Plugin da JMF.
2. Diagrama de efeitos da interface
3. Diagrama de estrutura funcional
4. Vários códigos para implementar funções
classe pública mymusicplayer implementa o ActionListener, controlerListener, runnable {jframe j = new jframe ("music player"); JLABEL TABLEPLAER = NEW JLABEL ("Playlist"); Jbutton badd = new jbutton ("add música"); Jbutton bdElect = new jbutton ("excluir música"); JButton bDelectTable = new JButton ("Lista Clear"); Jbutton bmovenext = new jbutton ("Next Song"); Jbutton bmoveprevious = new jbutton ("música anterior"); JButton BPlayer = New Jbutton ("Pausa"); Jbutton bstop = new jbutton ("stop"); JButton BSET = New JButton ("Show Lyrics"); JButton Bend = New JButton ("Stop"); String [] S = {"sequencial play", "Single Loop", "Shutter Play"}; // Opção suspensa da lista de suspensão Array JCOMBOBOX SELECT = novo JCOMBOBOX (S); // Crie opções suspensas jpanel p1 = new jpanel (); // área de playlist jpanel p = new jpanel (); Jpanel P2 = new jpanel (); // Área de botão jpanel p3 = new jpanel (); Jlabel l = new jlabel (); Jpanel p5 = new jpanel (); // coloque a lista de reprodução jpanel p6 = new jpanel (); // coloque o nome da música estática jpanel pp = new jpanel (); Jlabel estático lb; public static jtextarea jt = new jtextarea (); Índice estático int; // subscrito da lista de reprodução int conting; Int Flag; // é o marcador da lista de reprodução tocando aleatoriamente ou seqüencialmente tocando int contamSegund; // Obtenha o valor total do tempo da música estática int newTime = 0; int ischanging = 0; // Quando o mouse clicar no cursor, o valor de progresso também será alterado no ISPression = 0; // Defende se o mouse clica no arquivo cursor musicName = null; estático java.util.list <File> musicNames = null; // Use genéricos para criar arquivo de arquivo Arquivo currentDirectory = null; Lista de lista; // Lista de arquivos Filedialog Open; // define o objeto de diálogo de arquivo aleatório rand = new aleatom (); String filename; // barra de progresso jbutton timeinformation = new jbutton (); JSLIDER TIMESLIDER = novo JSLIDER (swingconstants.horizontal, 0, 100, 0); //(SwingConstants.horizontal) é usado para direcionar o conjunto de constantes com a barra de progresso como direção horizontal // (0, 100, 0), crie um deslizante horizontal com os valores mínimo, máximo e inicial especificado. // Play Player Player = NULL; MusicFileChooser filechooser = new MusicFileChooser (); estático jtextpane tp = new jtextpane (); // Mostrar área lírica estática jtextarea é = new jtextarea (); // mostra a área de imagem public mymusicplayer () {j.SetSize (1200, 700); J.SetLayout (NULL); j.getContentPane (). j.SetDefaultCloseoperation (jframe.exit_on_close); p.setbounds (2, 563, 1180, 95); p.setLayout (new BorderLayout ()); P1.setbounds (2, 3, 298, 30); p1.setbackground (nova cor (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 (nova cor (255.255.255)); p5.cliBounds (2, 35, 298, 526); p5.setLayout (nulo); p5.setbackground (nova cor (255.255.255)); P6.Setbounds (301, 3.880, 30); p6.setLayout (nulo); P6.setBackground (nova cor (255.255.255)); L.Setbounds (250, 4, 600, 30); // Defina a música exibida e tocada P6.Add (L); /*Implementar inserção de imagem**/imageicon ic = new Imageicon ("Image // 2.3.jpg"); ic = new imageicon (ic.getImage (). getScaledInstance (880, 477, 2)); // Obtenha a imagem e defina o tamanho da imagem lb = novo jlabel (IC); lb.setOpAque (falso); pp.setOpAque (falso); // Defina como PP. Are.setbounds (241, 56.990, 520); são.setOpAque (false); tp.setbackground (nova cor (255.255.255)); tp.setbounds (301, 35.880, 49); pp.add (são); pp.add (lb); // Lista de arquivos = nova lista (10); list.setbounds (100, 55, 187, 495); // List Area List.addactionListener (isto); J.Add (lista); J.Add (JT); J.Add (TP); Badd.setbounds (5,20, 90,30); Badd.setbackground (nova cor (255.255.255)); BDELECT. BDELECT.SetBackground (nova cor (255.255.255)); BDELECT. BDELECT.SetBackground (nova cor (255.255.255)); TabelaPlaer.setBounds (30, 100, 200, 50); TabelaPlaer.setFont (nova fonte ("安安", 1, 20)); P1.Add (TablePlaer); Bmoveprevious.setbackground (nova cor (255.255.255)); BPLAYER.setBackground (nova cor (255.255.255)); Bmovenext.setbackground (nova cor (255.255.255)); Bstop.setbackground (nova cor (255.255.255)); select.setbackground (nova cor (255.255.255)); Bset.setbackground (nova cor (255.255.255)); p2.add (bmoveprevious); P2.Add (BPLAYER); p2.add (bmovenext); p2.add (bstop); p2.add (selecione); p2.add (bset); p2.setbackground (nova cor (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 (isto); BdElect.addactionListener (isto); BDelectTable.addactionListener (isto); Bmovenext.addactionListener (isto); Bplayer.addactionListener (isto); Bmoveprevious.addactionListener (isto); Bstop.addactionListener (isto); select.addactionListener (this); Bset.addactionListener (isto); timeinformation.setEnabled (false); / * * Barra de progresso da implementação * */timeslider.setmajortickspacing (1); // Chame esse método para definir o intervalo da marca de escala principal. O número recebido representa a distância medida pelo valor entre cada marcador de escala principal. timeslider.setPaintTicks (true); // Para desenhar a escala principal, o setPaintticks deve ser definido como True TimesLider.addchangelistener (new Changelistener () {// crie um novo Changelistener e adicione -o ao slider. (int) (jslider) arg0.getsource ()). getValue (); timeslider.addmouseListener (new mouseAdApter () {public void mousePressed (mouseevent arg0) {isPressing = 1; // Quando o mouse clica no cursor} public void mouseLeardeed (mousevent arg0) {está pressionando = 0; quando o mouse não clica timeinformation.settext ("Hora atual: 00:00 || Tempo total: 00:00"); timeinformation.setbackground (nova cor (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); } / * * Função principal * * /public static void main (string [] args) lança ioexception, interruptedException {// interruptedException: Quando o thread está em um estado de espera, dormindo ou ocupado antes ou durante a atividade e o encadeamento é interrompido, a exceção é lançada. MyMusicPlayer play = new MyMusicPlayer (); Thread timerun = novo thread (reprodução); timerun.start (); } @Override public void ActionPerformed (ActionEvent E) {String cmd = E.getActionCommand (); // julgue se deve reproduzir ou pausar obtendo a string, string box = (string) select.getSelectedItem (); // julgue a ordem de reprodução if (e.getSource () == badd) {if (player == null) {if (filechooser.showpendialog (j) == musicFileChooser.Approve_Option) {this.musicName = filechooser.getSeletetedFile (); Arquivo CD = filechooser.getCurrentDirectory (); // Obtenha o caminho atual if (cd! = This.currentDirectory || this.currentDirectory == null) {fileFilter [] FILEFILTERS = FILECHOOSER.GetChoosableFileFilters (); // FileFilter é uma classe abstrata, que o jfileChooser usa para filtrar o conjunto de arquivos exibidos nos arquivos de arquivos do usuário [] = cd.listfiles (); //cd.listfiles () significa devolver uma matriz de nomes de pathNames abstratos, que representam arquivos no diretório representado por este nome de caminho abstrato. this.musicNames = new ArrayList <File> (); para (arquivo de arquivo: arquivos) {// sempre que o objeto de arquivo na matriz é atribuído à variável do arquivo e, em seguida, essa variável é operada no corpo do loop, como: // para (int i = 0; i <files.length; i ++) {file = files [i]; ...} nome = arquivo.getName (). // Obtenha todos os nomes de músicas para (filtro FileFilter: FileFilters) {if (! File.isDirectory () && filter.accept (file)) {this.musicnames.add (file); list.add (nome do arquivo); nome do arquivo = e.getActionCommand (); }}}}} index = MusicNames.IndexOF (MusicName); // define o subscrito da música count = musicNames.size (); Playfile (); }} else {player.start (); }} if (cmd.equals ("pausa")) {bplayer.settext ("play"); player.stop (); } if (cmd.equals ("play")) {bplayer.settext ("pausa"); player.start (); } if (e.getSource () == bstop) {// Stop if (player! = null) {player.stop (); TimeInformation.Settext ("Hora atual: 00: 00 || Tempo total: 00: 00"); timeslider.setValue (0); player.setMediAtime (New Time (0)); // Defina o tempo para zero}} if (e.getSource () == bmovenext) {// Próxima música if (player! = Null) {if ("sequal reprodução" .equals (caixa)) {nextMusic (); } if ("Playback do obturador" .equals (caixa)) {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 (); // Se você clicar na música anterior, a música atual será interrompida e a música anterior será tocada, tente {player = gerenciador.creteReAlizedPlayer (MusicNames.get (index) .Touri (). Tourl ()); player.prefetch (); player.setMediATime (novo Time (0,0)); // Play Player.addControllerListener (isto); L.Settext ("tocando:"+this.musicNames.get (index) .ToString ()); list.Select (índice); player.start (); sinalizador = 1; } Catch (noplayerexception | não é realizeException | ioexception e1) {e1.printStackTrace (); }}}}}} if (e.getSource () == bmoveprevious) {// música anterior if (player! = null) {if ("sequencial play" .equals (box)) {anteriormusic (); } if ("peças do obturador" .equals (caixa)) {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 (); // Se você clicar na música anterior, a música atual será interrompida e a música anterior será tocada, tente {player = gerenciador.creteReAlizedPlayer (MusicNames.get (index) .Touri (). Tourl ()); player.prefetch (); player.setMediATime (novo Time (0,0)); // comece a jogar Player.addControllerListener (isto); L.Settext ("tocando:"+this.musicNames.get (index) .ToString ()); list.Select (índice); player.start (); sinalizador = 1; } Catch (noplayerexception | não é realizeException | ioexception e1) {e1.printStackTrace (); }}}}}}} if (e.getSource () == bDelect) {// excluir índice de música = list.getSelectedIndex (); list.Remove (índice); MusicNames.remove (this.index); } if (e.getSource () == bDelectTable) {// limpe a lista list.removeall (); MusicNames.Removeall (MusicNames); player.stop (); jogador = nulo; } // Clique duas vezes na lista a ser tocada list.addmouselistener (new mouseAdapter () {public void mouseclicked (mouseevent e) {// clique duplo se (e.getClickCount () == 2) {if (player! }});} // Como a interface "ControllerListener" é implementada, esse método é usado para lidar com eventos transmitidos do mídia player; public void controllerUpdate (controlerent e) {string box = (string) select.getSelectedItem (); // julga a ordem de reprodução se (e a instância do endofMediaEvent) {player.SetMediATime (new Time (0)); if ("loop único" .equals (caixa)) {player.start (); } if ("play sequencial" .equals (caixa)) {nextMusic (); } if ("obtter play" .equals (caixa)) {if (this.musicNames! tente {player = gerenciador.CreameAlizedPlayer (MusicNames.get (index) .Touri (). TourL ()); player.prefetch (); player.setMediATime (novo Time (0,0)); // Play Player.addControllerListener (isto); L.Settext ("tocando:"+this.musicNames.get (index) .ToString ()); list.Select (índice); player.start (); sinalizador = 1; } Catch (noplayerexception | não é realizeException | ioexception e1) {e1.printStackTrace (); }}}}}}} / *** Obtenha o nome da música mp3** @mp3 File Path* @song nome* / public String getMusicName (string str) {int i; for (i = str.Length ()-1; i> 0; i-) {if (str.Charat (i) == '//') quebra; } str = str.substring (i + 1, str.length () - 4); retornar str; } / *** Próxima função de implementação* / public void nextMusic () {} / *** Função de implementação anterior* / public void anteriormusic () {} / *** reproduza o arquivo mp3 principal* / public void PlayFile () {try {player = gerente.CreameAlizedPlayer (musicNames.get (index). player.prefetch (); player.setMediATime (novo Time (0,0)); // Play Player.addControllerListener (isto); L.SetFont (New Font ("宋体", 0,20)); L.Settext ("tocando:"+this.musicNames.get (index) .ToString ()); // Mostra a música que está sendo tocada list.Select (Index); player.start (); Mythread11 tt = new mythread11 (); tt.start (); } catch (Exceção E1) {// Quando uma música não pode ser tocada, manuseie -o DealError (); retornar; } this.setFrame (); } public void setFrame () {countSecond = (int) player.getDuration (). getSeconds (); timeslider.setMaximum (CountSecond); timeslider.setValue (0); newTime = 0; } private void dealError () {// TODO Method Auto-Gerated Stub MusicNames.remove (Index); if ( - -count == índice) índice = 0; if (count == 0) player = null; else playfile (); }/*** Filtragem de arquivos mp3 Classe interna*/classe MusicFileChooser estende JfileChooser {}/*** Filtra de arquivo mp3 Classe interna auxiliar**/classe MyFileFilter Extrends FileFilter {// FileFilter é uma classe abstrata, que JFILECHOOSER usa para filtrar o filtro Descrição da sequência; public myFileFilter () {super (); } public myFileFilter (string [] sofr, string description) {super (); this.Suffaring = Suffarr; this.Descript = Descrição; } public boolean aceit (arquivo f) {for (string s: suffarr) {if (f.getName (). touppercase (). endswith (s)) {return true; }} return f.isdirectory (); } public string getDescription () {return this.Dection; }}/*** Leia a barra de progresso do tempo da exibição*/public void run () {while (true) {sleep (); if (player! = null) {if (isPressing == 0) {if (isChanging == 1) {newTime = timesLider.getValue (); player.setMediatime (novo Time ((((longo) novo)*1000000000); isCHANGing = 0; } else {newTime = (int) player.getMediATime (). getSeconds (); timeslider.setValue (newTime); timeInformation.Settext ("Hora atual:"+newtime/60+":"+newtime%60+"||"+"tempo total:"+contagem de segundos/60+":"+contagem de segundos%60); }}}}}}}}}} // thread que implementa as letras mythread11 estende o thread {public void run () {// TODO Auto-Gerated Method Stub Try {lrc lrc = readlrc.readlrc ("viajando luz.lrc"); Letras ls = parselrc.parselrc (LRC); Playtest (LS); } catch (Exceção e) {}}} estático void playtest (letra ls) lança interruptedException {tp.setFont (new Font ("宋体", 1,20)); tp.setforeground (color.blue); StyledDocument doc = tp.getStyledDocument (); SimpletTributeSet Center = new MallenteAttributeSet (); StyleConstants.Setalignment (centro, styleconstants.align_center); // mostra doc.setParagraphattributes (0, doc.getLength (), centro, false); tp.settext ("artista:" + ls.getar ()); tp.settext ("Álbum:" + ls.getal ()); tp.settext ("Song:" + ls.getti ()); tp.settext ("Produção de letras:" + ls.getby ()); for (lyric l: ls.getlyrics ()) {tp.settext (l.gettxt ()); Thread.sleep (l.gettimesize ()); }}}V. Resultados gerais dos testes
do seguinte modo
Para obter mais informações sobre o jogador, clique em "Java Player Function" para aprender.
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.