Java如何播放从文件选择器中选择的mp3文件

时间:2014-04-17 20:47:21

标签: java mp3 jfilechooser

您好我已经创建了一个文件选择器,我想知道是否有任何可能的方法来播放我可以从我的文件选择器中选择的mp3文件。如果是这样,怎么能实现呢?谢谢你提前的建议。所以当我点击一个文件时,没有什么事情发生我需要的是点击一个mp3文件,当我点击打开然后我可以听它。

这是我的文件选择器的代码。

  JFileChooser chooser = new JFileChooser();
       File F = new File("C:/");
       File namedir;
       File namepath;

       chooser.setCurrentDirectory(F);
       chooser.showOpenDialog(null);
       chooser.setDialogTitle("Choose file to play");
       chooser.setApproveButtonText("Play");
  namedir = chooser.getCurrentDirectory();
  namepath = chooser.getSelectedFile();
  System.out.print("the name of the the directory is "+namedir.getName());
  System.out.print("the name of the the path is "+namepath.getAbsolutePath());
   String fileName=null;

1 个答案:

答案 0 :(得分:3)

String fileName=null;
JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter(
        "MP3 Files", "mp3");
    chooser.setFileFilter(filter);
    int returnVal = chooser.showOpenDialog(parent);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
       fileName=     chooser.getSelectedFile().getName();
    }
MediaPlayer mediaPlayer = new MediaPlayer(new Media(fileName));
mediaPlayer.play();

以下是完整的工作代码

import java.net.URL;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.embed.swing.JFXPanel;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author Mayank Aggarwal
 */
public class MyAudio {

    public static void main(String[] args) {
        new MyAudio().start();
    }

    public void start() {

        String fileName = null;
        URL url;
        final CountDownLatch latch = new CountDownLatch(1);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new JFXPanel(); // initializes JavaFX environment
                latch.countDown();
            }
        });
        try {
            latch.await();
        } catch (InterruptedException ex) {
            Logger.getLogger(MyAudio.class.getName()).log(Level.SEVERE, null, ex);
        }
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
                "MP3 Files", "mp3");
        chooser.setFileFilter(filter);
        int returnVal = chooser.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            fileName = chooser.getSelectedFile().toURI().toString();

        }
        MediaPlayer mediaPlayer;
        mediaPlayer = new MediaPlayer(new Media(fileName));
        mediaPlayer.play();
    }
}