import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
/**
* Created with IntelliJ IDEA.
* User: jwang
* Date: 2018/3/9
* Time: 下午5:44
* To change this template use File | Settings | File Templates.
* Description:
*/
public class MP3Online {
private String filename;
private Player player;
private HttpURLConnection connection;// 存储连接
private int downed = 0;// 文加已下载大小,初始值为0
private URL fileurl;// 记录要下载文件的地址
private boolean isFile;
// constructor that takes the name of an MP3 file
public MP3Online(String filename,boolean isFile) {
this.filename = filename;
this.isFile=isFile;
}
public void close() {
if (player != null)
player.close();
}
// play the MP3 file to the sound card
public void play() throws JavaLayerException {
try {
if (isFile){
player=new Player(new BufferedInputStream(new FileInputStream(new File(filename))));
}else{
fileurl = new URL(filename);
connection = (HttpURLConnection) fileurl.openConnection();
connection.setRequestProperty("Range", "byte=" + this.downed + "-");
// BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
BufferedInputStream bis =downLoad();
player = new Player(bis);
}
} catch (Exception e) {
System.out.println("Problem playing file " + filename);
System.out.println(e);
}
// run in new thread to play in background
new Thread() {
public void run() {
try {
player.play();
} catch (Exception e) {
System.out.println(e);
}
}
}.start();
}
public BufferedInputStream downLoad(){
DefaultHttpClient httpClient = new DefaultHttpClient();
OutputStream out = null;
InputStream in = null;
try {
HttpGet httpGet = new HttpGet(filename);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
return new BufferedInputStream( entity.getContent());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 实现音乐在线播放 以及播放本地音乐文件
* @param args
* @throws JavaLayerException
* @throws IOException
*/
public static void main(String[] args) throws JavaLayerException, IOException {
String filename = "http://zhangmenshiting.qianqian.com/data2/music/538ad959e44474193335ec46914fc12f/318173809/318173809.mp3?xcode=debe49673761c3f5e23725bcf113dbcd";
MP3Online mp3 = new MP3Online(filename,false);
mp3.play();
}
}
评论0
最新资源