当前位置:编程学习 > JAVA >>

java制作一个MP3播放器,哪个高手帮忙看看代码

这是MusicPlayer.java

package com.test.audio;
import java.io.File;
import java.awt.BorderLayout;
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.List;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.amenuItem;
import java.awt.MenuShortcut;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
public class MusicPlayer extends Frame{
      boolean isStop=ture;
      boolean hasStop=ture;
 
      String filepath;
      String filename;
      AudioInputStream audioInputStream;
      AudioFormat audioFormat;
      SourceDataLine sourceDataLine;
      List list;
      Lable lablefilepath;
      Lable lablefilename;
    
      public MusicPlayer(){
          setLayout(new BorderLayout());
          setTitle("音乐播放器");
          setSize(350,370);
 
          MenuBar menubar=new MenuBar();
          Menu menufile=new Menu("文件");
          MenuItem menuopen=new MenuItem("打开",new MenuShortcut(KeyEvent.VK-O));
          menufile.add(menuopen);
          menufile.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                        open();
                 }
           });
          menubar.add(menufile);
          setMenuBar(menubar);
 
          list=new list(10);
          list.addMouseListener(new MouseAdapter(){
               public void mouseClicked(MouseEvent e){
                    if(e.getClickCount()==2){
                         filename=list.getSelectedItem();
                         play();
                     }
               }
          });
          add(list,"Center");
          Panel panel=new Panel(new GridLayout(2,1));
          labelfilepath=new Lable("播放目录:");
          lablefilename=new Lable("播放文件:");
          panel.add(labelfilepath);
          panel.add(labelfilename);
          add(panel,"North");

          addWindowListener(new WindowAdapter(){
                 public void windowClosing(WindowEvent e){
                         System.exit(0);
                 }
          });
          setVisible(true);
     }
     private void open(){
          FileDialog dialog=new FileDialog(this,"open",0);
          dialog.setVisible(true);
          filepath=dialog.getDirectory();
          if(filepath!=null){
               lablefilepath.setText("播放目录:"+filepath);
               list.removeAll();
               File filedir=new File(filepath);
               File[] filelist=filedir.listFiles();
               for(File file:filelist){
                    string filename=file.getName().toLowerCase();
                    if(filename.endsWith(".mp3")||filename.endsWith(".wav")){
                         list.add(filename);
                     }
                }
           }
      }
     private void play(){
          try{
              isStop=true;
              System.out.print("开始播放:"+filename);
              while(!hasStop){
                   System.out.print(".");
                   try{
                        Thread.sleep(10);
                   }catch(Exception e){
                    }
               }
               System.out.println("");
               File file=new File(filepath+filename);
               labelfilename.setText("播放文件:"+filename);
               audioInputStream=AudioSystem.getAudioInputSream(file);
               audioFormat=audioInputStream.getFormat();
               if(audioFormat.getEncoding()!=AudioFormat.Encording.PCM_SIGNED){
                    audioFormat=new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,audioFormat.getSampleRate(),16,audioFormat.getChannels(),audioFormat.getChannels()*2,audioFormat.getSampleRate(),false);
                    audioInputStream=AudioSystem.getAudioInputStream(audioFormat,audioInputStream);
               }
               DataLine.Info dataLineInfo=new DataLine.Info(sourceDataLine.class,audioFormat,AudioSystem.NOT_SPECIFIED);
               sourceDataLine=(SourceDataLine)AudioSystem.getLine(dataLineInfo);
               sourceDataLine.open(audioFormat);
               sourceDataLine.start();
              
               isStop=false;
               Thread playThread=new Thread(new PlayThread());
               playThread.star();
               }catch(Exception e){
                     e.printStackTrace();
                }
           }
           public static void main(String args[]){
                 new MusicPlayer();
            }
        }

这个是PlayThread.java

class PlayThread extends Thread
{
  byte tempBuffer[]=new byte[320];
  public void run()
  {
    try
    {
      int cnt;
      hasStop=false;
      while((cnt=audioInputStream.read(tempBuffer,0,tempBuffer.length))!=-1)
       {
         if(isStop)
           
           break;
         if(cnt>0)
         {
           sourceDataLine.write(tempBuffer,0,cnt); 
         }
         sourceDataLine.drain();
         sourceDataLine.close();
         hasStop=true;
        
          
       } 
       catch(Exception e)
       {
        e.printStackTrace();
        System.exit(0); 
       }
    } 
  } 
}

 

已经下载了J11.0.JAR,MP3SPLI.9.4.JAR ,tritonus_share.jar三个包

 

下一步应该怎么搞!书上写的不太清楚,我是初学者不是很明白

 

答案:您这程序抄错的挺多的,不过反正帮您改了,就给您贴出来。建议您以后用Eclipse或其它的开发软件写程序,这样可以提醒您编译错误的地方。
package com.test.audio;import java.io.File;import java.awt.BorderLayout;import java.awt.FileDialog;import java.awt.Frame;import java.awt.GridLayout;import java.awt.Label;import java.awt.List;import java.awt.Menu;import java.awt.MenuBar;import java.awt.MenuItem;import java.awt.MenuShortcut;import java.awt.Panel;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import javax.sound.sampled.AudioFormat;import javax.sound.sampled.AudioInputStream;import javax.sound.sampled.AudioSystem;import javax.sound.sampled.DataLine;import javax.sound.sampled.SourceDataLine;public class MusicPlayer extends Frame{boolean isStop = true;boolean hasStop = true;
String filepath;String filename;AudioInputStream audioInputStream;AudioFormat audioFormat;SourceDataLine sourceDataLine;List list;Label labelfilepath;Label labelfilename;
public MusicPlayer(){setLayout(new BorderLayout());setTitle("Music Player");setSize(350,370);
MenuBar menubar=new MenuBar();Menu menufile=new Menu("File");MenuItem menuopen=new MenuItem("Open",new MenuShortcut(KeyEvent.VK_O));menufile.add(menuopen);menufile.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){open();}});menubar.add(menufile);setMenuBar(menubar);
list = new List(10);list.addMouseListener(new MouseAdapter(){public void mouseClicked(MouseEvent e){if(e.getClickCount()==2){filename=list.getSelectedItem();play();}}});add(list,"Center");Panel panel=new Panel(new GridLayout(2,1));labelfilepath=new Label("Playing Directory: ");labelfilename=new Label("Play File: ");panel.add(labelfilepath);panel.add(labelfilename);add(panel,"North");addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});setVisible(true);}private void open(){FileDialog dialog=new FileDialog(this,"open",0);dialog.setVisible(true);filepath=dialog.getDirectory();if(filepath!=null){labelfilepath.setText("Playing Directory: "+filepath);list.removeAll();File filedir=new File(filepath);File[] filelist=filedir.listFiles();for(File file:filelist){String filename=file.getName().toLowerCase();if(filename.endsWith(".mp3")||filename.endsWith(".wav")){list.add(filename);}}}}private void play(){try{isStop=true;System.out.println("\nBegin Playing "+filename);while(!hasStop){System.out.print(".");try{Thread.sleep(10);}catch(Exception e){}}System.out.println("");File file=new File(filepath+filename);labelfilename.setText("Play File: "+filename);audioInputStream=AudioSystem.getAudioInputStream(file);audioFormat=audioInputStream.getFormat();if(audioFormat.getEncoding()!=AudioFormat.Encoding.PCM_SIGNED){audioFormat=new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,audioFormat.getSampleRate(),16,audioFormat.getChannels(),audioFormat.getChannels()*2,audioFormat.getSampleRate(),false);audioInputStream=AudioSystem.getAudioInputStream(audioFormat,audioInputStream);}DataLine.Info dataLineInfo=new DataLine.Info(SourceDataLine.class,audioFormat,AudioSystem.NOT_SPECIFIED);sourceDataLine=(SourceDataLine)AudioSystem.getLine(dataLineInfo);sourceDataLine.open(audioFormat);sourceDataLine.start();
hasStop=false;isStop=false;Thread playThread=new Thread(new PlayThread());playThread.start();}catch(Exception e){e.printStackTrace();}}public static void main(String args[]){new MusicPlayer();}
class PlayThread extends Thread{public void run(){try{int framesize = audioFormat.getFrameSize( );        byte[] buffer = new byte[4 * 1024 * framesize];int cnt;int numbytes = 0;while((cnt=audioInputStream.read(buffer, numbytes, buffer.length - numbytes))!=-1){numbytes += cnt;if(isStop)break;if(cnt>0){int bytestowrite = (numbytes/framesize)*framesize;sourceDataLine.write(buffer,0,bytestowrite);  int remaining = numbytes - bytestowrite;                if (remaining > 0)                    System.arraycopy(buffer,bytestowrite,buffer,0,remaining);                numbytes = remaining;}

} sourceDataLine.drain();sourceDataLine.close();hasStop=true;}catch(Exception e){e.printStackTrace();System.exit(0); }} }}
至于下一步,自然是编译和试运行了。从您的程序看来您没有用Eclipse(或其它编程工具),那么只能从command line来。您需要把自己的环境设置好(怎么设置可以去网上搜一下,哪怕就是问问,这样的贴也很多),然后把您的程序放到相应的位置(比如您的程序有package com.test.audio; 的定义,所以需要存在相同的路径下)。下面是给您示范的一个运行,您可以照样,只是改成您自己的路径:
C:\Project\BaseTest\src>dir com\test\audio\
 Volume in drive C has no label.
 Volume Serial Number is F8F6-B588

 Directory of C:\Project\BaseTest\src\com\test\audio

04/06/2010  04:06 PM    <DIR>          .
04/06/2010  04:06 PM    <DIR>          ..04/06/2010  04:03 PM             4,898 MusicPlayer.java
               1 File(s)          4,898 bytes
               2 Dir(s)  40,241,692,672 bytes free

C:\Project\BaseTest\src>javac com\test\audio\MusicPlayer.java

C:\Project\BaseTest\src>java -cp .;c:\Tech\MP3SPI\MpegAudioSPI1.9.4\mp3spi1.9.4.jar;c:\Tech\MP3SPI\MpegAudioSPI1.9.4\lib\jl1.0.jar;c:\Tech\MP3SPI\MpegAudioSPI1.9.4\lib\tritonus_share.jar com.test.audio.MusicPlayer
Begin Playing gaoyuanhong.mp3

上一个:Java实习.我头疼了..大家来说说看..
下一个:如何学习JAVA,并求个简单JAVA游戏代码

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,