缓存音频到本地

private MediaPlayermediaPlayer =new MediaPlayer();

private Stringpath; //网络音频

private String mp3String; //本地路径

private SharedPreferencesUtilspreferencesUtils;

private long videoTotalSize =0;

private StringlocalUrl;

private long videoCacheSize =0;

//再要播放的位置调用下面的逻辑

path = “网络音乐路径”;

    mp3String = (String)preferencesUtils.get(Contexts.MUSIC_PATH, "");

    if (!mp3String.equals(path)) {

        new Thread(new Runnable() {

@Override

            public void run() {

try {

mp3String =path;

                    preferencesUtils.put(Contexts.MUSIC_PATH, path);

                    prepareVideo(path);

                }catch (IOException e) {

e.printStackTrace();

                }

}

}).start();

    }else {

        localUrl = (String)preferencesUtils.get(Contexts.MUSIC_URL, "");

        try {

playMusicBySDCar(localUrl);

            Log.d("PATH", localUrl);

        }catch (IOException e) {

e.printStackTrace();

        }

}

}


/**

* 下载缓存音频

*

* @param remoteUrl

* @throws IOException

*/

private void prepareVideo(String remoteUrl)throws IOException {

URL url =new URL(remoteUrl);

    HttpURLConnection httpConnection = (HttpURLConnection) url

.openConnection();

    httpConnection.setConnectTimeout(3000);

    httpConnection.setRequestProperty("RANGE", "bytes=" +0 +"-");

    InputStream is = httpConnection.getInputStream();

    videoTotalSize = httpConnection.getContentLength();

    if (videoTotalSize == -1) {

return;

    }

String name = remoteUrl.substring(remoteUrl.lastIndexOf("/") +1);

    localUrl = Environment.getExternalStorageDirectory().getAbsolutePath()

+"/VideoCache/" + File.separator + name;

    //保存路径

    preferencesUtils.put(Contexts.MUSIC_URL, localUrl);

    File cacheFile =new File(localUrl);

    if (!cacheFile.exists()) {

cacheFile.getParentFile().mkdirs();

        cacheFile.createNewFile();

    }

RandomAccessFile raf =new RandomAccessFile(cacheFile, "rws");

    raf.setLength(videoTotalSize);

    raf.seek(0);

    byte buf[] =new byte[10 *1024];

    int size =0;

    videoCacheSize =0;

    int buffercnt =0;

    while ((size = is.read(buf)) != -1) {

try {

raf.write(buf, 0, size);

            videoCacheSize += size;

        }catch (Exception e) {

e.printStackTrace();

        }

}

is.close();

    raf.close();

    playMusicBySDCar(localUrl);

}

private void playMusicBySDCar(String localUrl)throws IOException {

mediaPlayer.setDataSource(localUrl);

    mediaPlayer.prepare();

    mediaPlayer.start();

    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

@Override

        public void onCompletion(MediaPlayer mp) {

mp.reset();

        }

});

}

你可能感兴趣的:(缓存音频到本地)