java怎么播放本地音乐?????????????????

解决方案 »

  1.   

    不用swing,我的要求就是一段程序可以读取我的音乐文件就可以了
      

  2.   

    lz说的是不是用java程序调用播放器然后播放音乐?
      

  3.   

    swting里面有的,百度一下就可以找到了
      

  4.   

    public void play(String Filename) 
      { 
      try{ 
      // 用输入流打开一音频文件 
      InputStream in = new FileInputStream(Filename);//FIlename 是你加载的声音文件如(“game.wav”) 
      // 从输入流中创建一个AudioStream对象 
      AudioStream as = new AudioStream(in); 
      AudioPlayer.player.start(as);//用静态成员player.start播放音乐 
      //AudioPlayer.player.stop(as);//关闭音乐播放 
      //如果要实现循环播放,则用下面的三句取代上面的“AudioPlayer.player.start(as);”这句 
      /*AudioData data = as.getData(); 
      ContinuousAudioDataStream gg= new ContinuousAudioDataStream (data); 
      AudioPlayer.player.start(gg);// Play audio. 
      */ 
      //如果要用一个 URL 做为声音流的源(source),则用下面的代码所示替换输入流来创建声音流: 
      /*AudioStream as = new AudioStream (url.openStream()); 
      */ 
      } catch(FileNotFoundException e){ 
      System.out.print("FileNotFoundException "); 
      } catch(IOException e){ 
      System.out.print("有错误!"); 
      } 
      }
      

  5.   

    在javax.swing.sound里面找吧,java本身只能支持mid格式的,其他的格式要自己写插件扩展哦。最近我也在尝试着这个问题呢!
      

  6.   

    如何你指定了MP3默认的播放类型。
    那么通过runtime直接在程序中打开就行了。String file="c:\\歌曲名.mp3";
         Runtime.getRuntime().exec("cmd /c start "   +   file.replaceAll(" ", "\" \""));
      

  7.   

    建议使用jmf(java media framwork),这样就能播放mp3等众多格式的音乐了;去sun官网下一个jmf,安装好后,把jmf.jar包引入便可使用,给出例zi代码:使用方法:构造函数中传入文件路径名即可,播放、暂停、继续、停止等功能均已实现。 /*************************************************
      * Subclass: MusicPlay
      *************************************************/
     public class MusicPlay implements Runnable {
      private Time zeroTime = new Time(0);
      private Player player;
      private boolean isloop = false;  /*************************************************
       * Function: MusicPlay Description: constructor, load the music file and
       * get ready for play Called By: MultiMedia()
       *************************************************/
      // 实例化各个参数 filename 为文件名,可为绝对路径
      public MusicPlay(String filename) {
       File file = new File(filename);
       try {
        player = Manager.createRealizedPlayer(file.toURI().toURL());
        player.addControllerListener(new ControllListener());
       } catch (NoPlayerException e) {
        e.printStackTrace();
       } catch (CannotRealizeException e) {
        e.printStackTrace();
       } catch (MalformedURLException e) {
        e.printStackTrace();
       } catch (IOException e) {
        e.printStackTrace();
       }
      }  /*************************************************
       * Function: isRunning Description: test if this music is playing Called
       * By:
       *************************************************/
      public boolean isRunning() {
       return player.getState() == Player.Started;
      }  /*************************************************
       * Function: play Description: play the music for once Called By:
       * resumeAll()
       *************************************************/
      // 只播放一次
      public void play() {
       if (!turnOff)
        player.start();
      }  /*************************************************
       * Function: replay Description: replay the music Called By: musics that
       * will be played many times will invoke this methed
       *************************************************/
      // 再播放一次
      public void replay() {
       if (turnOff)
        return;   if (player.getState() == Controller.Prefetched)
        player.setMediaTime(zeroTime);
       player.start();
      }  /*************************************************
       * Function: stop Description: stop this music Called By: stopAll() of
       * upper class,suspendAll() of upper
       * class,BackroundForMenuPanel,GameOverPanel
       *************************************************/
      public void stop() {
       player.stop();
      }  /*************************************************
       * Function: close Description: dispose the music Called By: closeAll()
       * of super class
       *************************************************/
      public void close() {
       player.stop();
       player.close();
      }  /*************************************************
       * Function: loop Description: make the music played repetitiously
       * Called By: music that will repetitious play
       *************************************************/
      // 循环播放
      public void loop() {
       if (turnOff)
        return;   isloop = true;
       player.prefetch();
       replay();
      }  /*************************************************
       * Function: run Description: trig this music Called By: Override method
       *************************************************/
      @Override
      public void run() {
       loop();
      }  /*************************************************
       * Subclass: ControllListener Description: listener for playing and
       * implement playing repetitiously
       *************************************************/
      // 通过对播放进度的监听,实现循环播放
      private class ControllListener implements ControllerListener {   public void controllerUpdate(ControllerEvent e) {
        if (e instanceof EndOfMediaEvent) {
         if (isloop) {
          player.setMediaTime(new Time(0));
          player.start();
         }
        }
       }
      } } 
      

  8.   

    JMF   java media  framework   
      

  9.   

    目前的版本是  JMF2.1  你需要将其安装  然后 将lib目录下的文件引入工程
    package com;
    import java.io.File;
    import java.io.IOException;
    import java.net.MalformedURLException;import javax.media.CannotRealizeException;
    import javax.media.Controller;
    import javax.media.ControllerEvent;
    import javax.media.ControllerListener;
    import javax.media.EndOfMediaEvent;
    import javax.media.Manager;
    import javax.media.NoPlayerException;
    import javax.media.Player;
    import javax.media.Time;/*******************************************************************************
     * Subclass: MusicPlay
     ******************************************************************************/
    public class MusicPlay implements Runnable {
    private Time zeroTime = new Time(0);
    private Player player;
    private boolean turnOff = false;
    private boolean isloop = false; /***************************************************************************
     * Function: MusicPlay Description: constructor, load the music file and get
     * ready for play Called By: MultiMedia()
     **************************************************************************/
    // 实例化各个参数 filename 为文件名,可为绝对路径
    public MusicPlay(String filename) {
    File file = new File(filename);
    try {
    player = Manager.createRealizedPlayer(file.toURI().toURL());
    player.addControllerListener(new ControllListener());
    } catch (NoPlayerException e) {
    e.printStackTrace();
    } catch (CannotRealizeException e) {
    e.printStackTrace();
    } catch (MalformedURLException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    } /***************************************************************************
     * Function: isRunning Description: test if this music is playing Called By:
     **************************************************************************/
    public boolean isRunning() {
    return player.getState() == Player.Started;
    } /***************************************************************************
     * Function: play Description: play the music for once Called By:
     * resumeAll()
     **************************************************************************/
    // 只播放一次
    public void play() {
    if (!turnOff)
    player.start();
    } /***************************************************************************
     * Function: replay Description: replay the music Called By: musics that
     * will be played many times will invoke this methed
     **************************************************************************/
    // 再播放一次
    public void replay() {
    if (turnOff)
    return; if (player.getState() == Controller.Prefetched)
    player.setMediaTime(zeroTime);
    player.start();
    } /***************************************************************************
     * Function: stop Description: stop this music Called By: stopAll() of upper
     * class,suspendAll() of upper class,BackroundForMenuPanel,GameOverPanel
     **************************************************************************/
    public void stop() {
    player.stop();
    } /***************************************************************************
     * Function: close Description: dispose the music Called By: closeAll() of
     * super class
     **************************************************************************/
    public void close() {
    player.stop();
    player.close();
    } /***************************************************************************
     * Function: loop Description: make the music played repetitiously Called
     * By: music that will repetitious play
     **************************************************************************/
    // 循环播放
    public void loop() {
    if (turnOff)
    return; isloop = true;
    player.prefetch();
    replay();
    } /***************************************************************************
     * Function: run Description: trig this music Called By: Override method
     **************************************************************************/

    public void run() {
    loop();
    } /***************************************************************************
     * Subclass: ControllListener Description: listener for playing and
     * implement playing repetitiously
     **************************************************************************/
    // 通过对播放进度的监听,实现循环播放
    private class ControllListener implements ControllerListener { public void controllerUpdate(ControllerEvent e) {
    if (e instanceof EndOfMediaEvent) {
    if (isloop) {
    player.setMediaTime(new Time(0));
    player.start();
    }
    }
    }
    }
    public static void main(String[] args) {
    MusicPlay mp = new MusicPlay("w.mp3");
    mp.play();

    }}
      

  10.   

    为了支持MP3的播放,我们必须添加MP3的SPI支持库。首先需要下载MP3的支持库。官方网站:http://www.javazoom.net/。下载页面:http://www.javazoom.net/mp3spi/sources.html。下载地址:http://www.javazoom.net/mp3spi/sources/mp3spi1.9.4.zip。下载文件:mp3spi1.9.4.zip。将mp3spi1.9.4.zip中的3个JAR文件jl1.0.jar 、mp3spi1.9.4.jar 、tritonus_share.jar添加到当前项目中即可。下面我们来实现一个MP3音乐播放器,实现的功能是:选择"文件"→"打开"命令弹出文件选择对话框,将选择目录的所有MP3和WAV文件加入到播放列表中,双击播放列表中的音乐文件实现音乐的播放和切换。要实现该程序,首先需要提供了一个主程序窗口,该窗口提供了各种界面组件和操作事件的控制,并包含一个音乐播放的子线程,子线程由主线程控制。因此有以下两个类。音乐播放器主程序MusicPlayer.java。播放线程PlayThread.java。(1)音乐播放器主程序MusicPlayer.java该类继承自Frame类,首先需要为该类添加文件播放的5个变量:String filepath;     //播放文件目录String filename;     //播放文件名称AudioInputStream audioInputStream;  //文件流AudioFormat audioFormat;   //文件格式SourceDataLine sourceDataLine;  //输出设备
     并添加一个录音标志开关,控制录音的开始与停止:boolean isStop = true;    //控制播放线程boolean hasStop = true;    //播放线程状态 同时添加几个显示界面组件:List list;      //文件列表Label labelfilepath;    //播放目录显示标签Label labelfilename;    //播放文件显示标签 在该程序的构造函数中,需要分别创建主窗体、菜单栏、文件列表组件、信息显示面板。并为菜单栏注册单击事件,为文件列表组件注册鼠标事件,为窗体注册关闭事件。在菜单栏中选择"打开"选项时,执行打开函数open(),用以打开文件选择对话框,将选择目录的MP3和WAV文件添加到列表组件中。文件列表组件在被鼠标双击时,取得被选择的文件名,并取得被选择的文件名,然后调用播放函数play()进行播放。窗口关闭事件发生时调用System.exit(0)退出程序。play()函数中在播放录音时,调用的是内部播放线程PlayThread.java来进行播放。该函数中首先会设置音乐的停止标志isStop=true,子线程在发现该变量为true时就会停止当前音乐的播放;由于从接收到停止指令到停止音乐的播放会需要一段时间,所以需要在play()中根据hasStop来执行一段时间的暂停,当子线程结束后该变量就会为true,此时play()函数就会继续执行,读取音乐文件,并进行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.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("MP3音乐播放器");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 Label("播放目录:");labelfilename = new Label("播放文件:");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("播放目录:" + 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.getAudioInputStream(file);audioFormat = audioInputStream.getFormat();//转换MP3文件编码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();            //创建独立线程进行播放isStop = false;Thread playThread = new Thread(new PlayThread());playThread.start();} catch (Exception e) {e.printStackTrace();}}    public static void main(String args[]) {new MusicPlayer();}}在该主程序中添加一个入口主函数main()来启动该主程序即可。
    2)播放线程PlayThread.java在主程序的播放函数play()中,调用了播放线程进行播放。该线程与录音机中的播放线程相似,不同的是它需要根据isStop指令来检查是否应该终止当前的播放线程。另外,该线程在播放结束后,还应该设置hasStop=true,告诉play()函数该线程已经停止了,可以继续下一首音乐的播放了。该程序的代码如下:播放线程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);}}//Block等待临时数据被输出为空sourceDataLine.drain();sourceDataLine.close();hasStop = true;} catch (Exception e) {e.printStackTrace();System.exit(0);}}}(3)运行MP3音乐播放器完成以上代码后,即可运行主程序MusicPlayer,就会显示。
      

  11.   

    http://download.csdn.net/detail/chinaluopiao/3560841  这个资源实现了播放,不过资源挺贵的,不知道你有木有那么多积分!!