android 播放网络音频

1.确保app申请了网络权限

2.如果音频是http开头设置运行http 

3.添加代码 网络资源尽量要设置异步 不如资源不存在的话会阻塞

private void playOnlineSound(String soundUrlDict) {
        try {
            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(soundUrlDict);
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    mediaPlayer.start();
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (mp != null) {
                        mp.release();
                    }

                }
            });
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {

                    return false;
                }
            });
        } catch (IOException e1) {

        }
    }

2.实验音频存在的情况

//创建一个MediaPlayer对象
        MediaPlayer mp3 = new MediaPlayer();
//设置音频数据路径(下方为示例)
        try {
            mp3.setDataSource("http://qiniu.cunzhuang.top/%E5%85%AD%E5%93%B2%20-%20%E4%BD%A0%E7%9A%84%E5%BF%83%E6%98%AF%E5%90%A6%E4%B9%9F%E6%9C%89%E6%88%91%E7%9A%84%E5%90%8D.mp3");
            mp3.setAudioStreamType(AudioManager.STREAM_MUSIC);
            //mediaPlayer.prepare();//同步的准备方法。
            mp3.prepareAsync();//异步的准备
            mp3.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();

                }
            });
            mp3.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {

                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

 

作者:张学涛

-------------------------------------------

我不是代码的生产者,只是代码的搬运工

posted @ 2021-01-13 23:26  张学涛  阅读(525)  评论(0编辑  收藏  举报