我正在写一个可以从Http玩的小玩家 . 媒体播放器可以使用 mPlayer.setDataSource(url); 从http流播放mp3,但我想保存此文件 . 我试过以下:

public static void downloadFile(File f, String songUrl, IDownloadListener listener)throws Exception{
    URL url = new URL(songUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(5000);
    connection.setRequestMethod("GET");
    connection.setDoInput(true);
    InputStream inStream = connection.getInputStream();
    FileOutputStream outStream = new FileOutputStream(f);

    Integer fileLength = connection.getContentLength();
    try {
        byte data[] = new byte[16384];

        int lastPercentNotify = -1, curPercent;
        int count;
        int total = 0;

        listener.onFileDescriptorAvailable(outStream.getFD());   //!!!! this willnotify about FD

        while ((count = inStream.read(data, 0, data.length)) != -1){
            total += count;
            outStream.write(data, 0, count);
            curPercent = (total * 100) / fileLength;

            if (curPercent != lastPercentNotify && listener != null && curPercent % 10 == 0){
                listener.onDownload(f.getName(), curPercent, 100);
                lastPercentNotify = curPercent;
            }
        }
    }finally {
        inStream.close();
        outStream.close();
    }
}

在我的听众中我做了以下事情:

mPlayer.setDataSource(fileDescr);
//prepare and call mPlayer.start()

但是当我想要改变描述符时,我有各种例外 .

UPD: 我的代码适用于保存文件 . 我麻烦的是播放mp3并同时保存到SD卡 .