一个基于JMF的超简易型MP3播放器

import  java.awt.Font;
import  java.awt.Image;
import  java.awt.Toolkit;
import  java.awt.event.WindowAdapter;
import  java.awt.event.WindowEvent;
import  java.io.File;
import  java.io.IOException;
import  java.io.RandomAccessFile;
import  java.net.MalformedURLException;
import  java.net.URL;
import  java.util.Calendar;
import  java.util.Enumeration;
import  java.util.GregorianCalendar;

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.PrefetchCompleteEvent;
import  javax.media.RealizeCompleteEvent;
import  javax.media.Time;
import  javax.swing.JFileChooser;
import  javax.swing.JFrame;
import  javax.swing.JTextArea;
import  javax.swing.UIManager;
import  javax.swing.filechooser.FileNameExtensionFilter;
import  javax.swing.plaf.FontUIResource;


public   class  MiniPlayer  extends  JFrame  implements  Runnable  {
    
/**
     * 
     
*/

    
private static final long serialVersionUID = 1L;
    
/*************************************************************************
     * 主函数 / 静态方法
     ************************************************************************
*/

    
public static void main(String[] args) {
        MiniPlayer mp 
= new MiniPlayer();
        
new Thread(mp,"Relyn").start();
    }

    
/*************************************************************************
     * 变量 / 常量
     ************************************************************************
*/

    
/**
     * 音频文件路径
     
*/

    
private String filepath;
    
/**
     * 音频文件名
     
*/

    
private String filename;
    
/**
     * 音频文件
     
*/

    
private File file;
    
/**
     * MP3文件的标题
     
*/

    
private String songname;
    
/**
     * MP3信息
     
*/

    
private SongInfo info;
    
/**
     * 文件URL
     
*/

    
private URL url = null;
    
/**
     * 界面组件的缺省字体
     
*/

    
private static final Font DEFAULT_FONT = new Font("微软雅黑", Font.PLAIN, 12);
    
/*************************************************************************
     * 构造函数
     ************************************************************************
*/

    
public MiniPlayer() {
        
//什么也不做
    }

    
/*************************************************************************
     * 方法
     ************************************************************************
*/

    
/**
     * 设置界面组件的缺省字体
     * 
@param font 字体
     
*/

    
private static void setUIFont(Font font)
    
{
        Enumeration
<Object> keys = UIManager.getDefaults().keys();
        
        
while(keys.hasMoreElements())
        
{
            Object key 
= keys.nextElement();
            Object value 
= UIManager.get(key);
            
            
if(value instanceof FontUIResource)
            
{
                UIManager.put(key, font);
            }

        }

    }

    
/**
     * 线程接口函数
     
*/

    
public void run() {
        
try {
            UIManager.setLookAndFeel(
"javax.swing.plaf.metal.MetalLookAndFeel");
            setUIFont(DEFAULT_FONT);
        }
 catch(Exception e) {
            e.printStackTrace();
        }

        MyChooser mc 
= new MyChooser("F:/KuGoo");
        filepath 
= mc.getFilepath();
        
if (filepath == null) System.exit(0);
        filename 
= mc.getFilename();
        file 
= mc.getFile();
        
try {
            RandomAccessFile ra 
= new RandomAccessFile(file, "r");
            
byte[] buffer = new byte[128];
            ra.seek(ra.length() 
- 128);
            ra.read(buffer);
            info 
= new SongInfo(buffer);
            
if (info.getSongName().equals(""|| info.getArtist().equals("")) songname = filename;
            
else songname = info.getArtist()+" - "+info.getSongName();
        }
 catch (Exception e) {}
        filepath 
= "file:" + filepath;
        openFile();
    }

        
/*
        if (fd == null) 
        {
            fd = new FileDialog(MiniPlayer.this, "打开文件",
                               FileDialog.LOAD);
        }
        fd.setVisible(true);
        if (fd.getFile() != null) 
        {
            filename = fd.getDirectory() + fd.getFile();
            File file = new File(filename);
            try {
                RandomAccessFile ra = new RandomAccessFile(file, "r");
                byte[] buffer = new byte[128];
                ra.seek(ra.length() - 128);
                ra.read(buffer);
                info = new SongInfo(buffer);
            } catch (Exception e) {} 
            songName = info.getArtist()+" - "+info.getSongName();
            openFile("file:" + filename);       
        }
*/

    
/**
     * 打开音频文件
     
*/

    
public void openFile() {
        
try {
            url 
= new URL(filepath);
        }
 catch (MalformedURLException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }

        
new PlayerBoard(url, songname);//新建立一个播放窗口
    }

}

/**
 * 文件选择器
 
*/

class  MyChooser  extends  JFileChooser  {
    
/**
     * 
     
*/

    
private static final long serialVersionUID = 1L;
    
/*************************************************************************
     * 变量 / 常量
     ************************************************************************
*/

    
/**
     * 音频文件名
     
*/

    
private String filepath;
    
/*************************************************************************
     * 构造函数
     ************************************************************************
*/

    
public MyChooser (String title) {
        
super(title);
        FileNameExtensionFilter filter 
= new FileNameExtensionFilter(
                
"音频文件(*.mp3;*.wav)""mp3""wav");
            
this.setFileFilter(filter);
            
int returnVal = this.showOpenDialog(this);
            
if(returnVal == JFileChooser.APPROVE_OPTION) {
                filepath 
= this.getSelectedFile().toString();
            }

    }

    
/*************************************************************************
     * 方法
     ************************************************************************
*/

    
/**
     * 音频文件名
     
*/

    
public String getFilename() {
        
return this.getSelectedFile().getName();
    }

    
/**
     * 音频文件路径
     
*/

    
public String getFilepath() {
        
return filepath;
    }

    
/**
     * 音频文件
     
*/

    
public File getFile() {
        File file 
= this.getSelectedFile();
        
return file;
    }

}

/**
 * 播放面板类
 
*/

class  PlayerBoard  extends  JFrame  implements  ControllerListener  {
    
/**
     *
     
*/

    
private static final long serialVersionUID = 1L;
    
/*************************************************************************
     * 变量 / 常量
     ************************************************************************
*/

    
/**
     * 音乐文件名
     
*/

    
private String title = null;
    
/**
     * 文本输入区
     
*/

    
public JTextArea text = new JTextArea();
    
/**
     * 曲目时间
     
*/

    
private String time;
    
/**
     * 曲目总时间
     
*/

    
private int maxTime;
    
private String limitTime = "";
    
/**
     * 曲目当前秒数
     
*/

    
private int currentSeconds, currentSecond;
    
/**
     * 时间管理类
     
*/

    
private GregorianCalendar calendar = new GregorianCalendar();
    
/**
     * 播放器
     
*/

    
private Player player;
    
/**
     * 是否正在播放
     
*/

    
private boolean isplaying = false;
    
/**
     * 面板默认字体
     
*/

    
private Font f = new Font("微软雅黑", Font.PLAIN, 12);
    
/*************************************************************************
     * 构造函数
     ************************************************************************
*/

    
public PlayerBoard(URL url, String title) 
    
{
        
super("Relyn Player");
        Image icon 
= Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("title.gif"));   
        
this.setIconImage(icon);   
        setVisible(
true);
        setSize(
250,65);
        
this.title = title;
        text.setFont(f);
        add(text);
        
try {
            player 
= Manager.createPlayer(url);
        }
 catch (NoPlayerException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }
 catch (IOException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }

        player.addControllerListener((ControllerListener) 
this);
        player.realize();
        addWindowListener( 
new WindowAdapter() {
            
public void windowClosing(WindowEvent we) {
            System.exit(
0);
            }

        }
 );
    }

    
/*************************************************************************
     * 方法
     ************************************************************************
*/

    
public void controllerUpdate(ControllerEvent ce) 
    
{
        
if (ce instanceof RealizeCompleteEvent) 
        
{
            player.prefetch();
        }

        
else if (ce instanceof PrefetchCompleteEvent)
        
{
            maxTime 
= Math.round((float)player.getDuration().getSeconds());
            calendar.setTimeInMillis(maxTime 
* 1000);
            limitTime 
= PlayerBoard.getTimeFormat(calendar);
            player.start();
            isplaying 
= true;
        }

        
else if (ce instanceof EndOfMediaEvent)
        
{
            endMusic();
        }

        
while (isplaying == true{
            currentSeconds 
= Math.round((float)player.getMediaTime().getSeconds());
            calendar.setTimeInMillis(currentSeconds 
* 1000);
            time 
= PlayerBoard.getTimeFormat(calendar).replaceAll(" ","");
            text.setText(
"正在播放:" + title + " 曲目时间:" + time + "-" + limitTime);
            
try {
                Thread.sleep(
1000);
            }
 catch (InterruptedException e) {
                
// TODO Auto-generated catch block
                e.printStackTrace();
            }

            currentSecond 
= Math.round((float)player.getMediaTime().getSeconds());
            
if (currentSecond == currentSeconds) isplaying = false;
        }

    }

    
/**
     * 转换时间格式
     
*/

    
private static String getTimeFormat(GregorianCalendar calendar) {
        String text 
= "";
        
if(calendar.get(Calendar.MINUTE) < 10)text += "0" + calendar.get(Calendar.MINUTE);
        
else text += calendar.get(Calendar.MINUTE);
        
if(calendar.get(Calendar.SECOND) < 10)text += ":0" + calendar.get(Calendar.SECOND);
        
else text += ":" + calendar.get(Calendar.SECOND);
        
return text;
    }

    
/**
     * 播放完毕的处理
     
*/

    
protected void endMusic() {
        player.setMediaTime(
new Time(0));
        isplaying 
= true;
        player.start();
    }

}

 这个MP3播放器只能播放一首歌,如果要播另一首要重新启动一次,所以,不实用。。仅供参考

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值