Mp3Player播放MP3音乐文件

package com.imooc.test;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javazoom.jl.decoder.Bitstream;
import javazoom.jl.decoder.BitstreamException;
import javazoom.jl.decoder.Header;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

/**
 * 
 * @ClassName: Mp3Player
 * @Description: TODO(播放.mp3 音乐文件)
 * @author Long
 * @date 2015年9月15日 下午3:02:09
 */
public class Mp3Player {

	/**
	 * 
	 * @Title: getMp3Time
	 * @Description: TODO(获取mp3文件的播放时间)
	 * @author fyf
	 * @return time(00:00)
	 */
	public String getMp3Time(String mp3FilePath) {

		try {
			File file = new File(mp3FilePath);

			if (file.exists() && file.isFile()) {
				FileInputStream fis = new FileInputStream(file);
				int bytes = fis.available();

				Bitstream bit = new Bitstream(fis);
				Header header = bit.readFrame();
				long time = (long) header.total_ms(bytes);

				return formatTime(time);
			}
		} catch (IOException | BitstreamException e) {
			System.out.println(e);
		}

		return null;
	}

	/**
	 * 
	 * @Title: formatTime
	 * @Description: TODO(格式化时间:mm:ss;分:秒)
	 * @author fyf
	 * @return time(00:00)
	 */
	public String formatTime(long time) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("mm:ss");

		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(time);

		return dateFormat.format(calendar.getTime());
	}

	/**
	 * 
	 * @Title: playerMp3
	 * @Description: TODO(播放mp3)
	 * @author fyf
	 * @param mp3File
	 *            mp3文件路径
	 */
	public void playerMp3(String mp3FilePath) {
		BufferedInputStream buffer = null;

		/**
		 * 获取文件数据流
		 */
		try {
			buffer = new BufferedInputStream(new FileInputStream(mp3FilePath));
		} catch (Exception e) {
			try {
				buffer = new BufferedInputStream(new URL(mp3FilePath).openStream());
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}

		try {
			Player player = new Player(buffer);
			player.play();
		} catch (JavaLayerException e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		Mp3Player mp3Player = new Mp3Player();
		//播放本地文件
		String mp3FilePath = "D:\\CloudMusic\\命中注定.mp3";
		String mp3Time = mp3Player.getMp3Time(mp3FilePath);
		System.out.println("当前音乐时间长度:"+mp3Time);
		mp3Player.playerMp3(mp3FilePath);

		// 播放网络文件
		mp3FilePath = "http://music.baidutt.com/up/kwcawscw/yyaumy.mp3";
		mp3Player.playerMp3(mp3FilePath);
		

	}
}

 需要导入包"jl1.0.1.jar".

下载地址:http://download.csdn.net/download/junlong750/9463231

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值