java 實現網易雲音樂下載和播放

不廢話  直接上代碼

 

首先 是下載工具類 根據url 下載文件

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;

/**
 * Java原生的API可用於發送HTTP請求,即java.net.URL、java.net.URLConnection,這些API很好用、很常用,
 * 但不夠簡便;
 * 
 * 1.通過統一資源定位器(java.net.URL)獲取連接器(java.net.URLConnection) 2.設置請求的參數 3.發送請求
 * 4.以輸入流的形式獲取返回內容 5.關閉輸入流
 * 
 * @author LZH
 *
 */
public class HttpConnectionUtil {


    /**
     * 
     * @param urlPath
     *            下載路徑
     * @param downloadDir
     *            下載存放目錄
     * @return 返回下載文件路徑
     */
    @SuppressWarnings("finally")
	public static String downloadFile(String urlPath, String downloadDir) {
        File file = null;
        String path=null;
        try {
            // 統一資源
            URL url = new URL(urlPath);
            // 連接類的父類,抽象類
            URLConnection urlConnection = url.openConnection();
            // http的連接類
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            // 設定請求的方法,默認是GET
            httpURLConnection.setRequestMethod("POST");
            // 設置字符編碼
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 打開到此 URL 引用的資源的通信鏈接(如果尚未建立這樣的連接)。
            httpURLConnection.connect();

            // 文件大小
            int fileLength = httpURLConnection.getContentLength();

            // 文件名
            String filePathUrl = httpURLConnection.getURL().getFile();
            String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);

//            System.out.println("file length---->" + fileLength);

            URLConnection con = url.openConnection();

            BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());

             path = downloadDir + File.separatorChar + fileFullName;
            
            file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            OutputStream out = new FileOutputStream(file);
            int size = 0;
            int len = 0;
            byte[] buf = new byte[1024];
            while ((size = bin.read(buf)) != -1) {
                len += size;
                out.write(buf, 0, size);
                // 打印下載百分比
                // System.out.println("下載了-------> " + len * 100 / fileLength +
                // "%\n");
            }
            bin.close();
            out.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            return path;
        }

    }

}

然後是播放類


import java.io.BufferedInputStream;
import java.io.FileInputStream;

import javazoom.jl.player.Player;

public class MP3Player {
    private String filename;
    private Player player;

    public MP3Player(String filename) {
        this.filename = filename;
    }

    public void play() {
        try {
            BufferedInputStream buffer = new BufferedInputStream(new FileInputStream(filename));
            player = new Player(buffer);
            player.play();

        } catch (Exception e) {
            System.out.println(e);
        }
    }
    public void stop() {
    	try {
    		player.close();
    		
    	} catch (Exception e) {
    		System.out.println(e);
    	}
    }
}

重點來啦   這個 id 是搜索出來歌曲的url id

id=316277


public class Test {

	public static void main(String[] args) {
        // 下載文件測試
		String downloadFile = HttpConnectionUtil.downloadFile("http://music.163.com/song/media/outer/url?id=316277", "D:\\cer");
		System.out.println("下載返回的地址:"+downloadFile);
		try {
			//等待下載
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 MP3Player mp3 = new MP3Player(downloadFile);
	        //播放
	     mp3.play(); 
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章