Android-MediaPlayer播放网络音频

官方文档:https://developer.android.google.cn/reference/android/media/MediaPlayer

运行截图: 

Android-MediaPlayer播放网络音频_第1张图片

 主布局文件:




    

    

        

主类:

/***
 * 该Demo是演示MediaPlayer播放网络音频
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button start;
    private Button pause;

    private MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        initMediaPlayer();
    }

    private void initMediaPlayer() {
        try {
            mediaPlayer.setDataSource("http://www.ytmp3.cn/down/57799.mp3");
            mediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void init() {
        start = findViewById(R.id.start);
        pause = findViewById(R.id.pause);
        start.setOnClickListener(this);
        pause.setOnClickListener(this);
        mediaPlayer = new MediaPlayer();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start:
                if (!mediaPlayer.isPlaying()) {
                    mediaPlayer.start();
                }
                break;
            case R.id.pause:
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }
}
//音乐地址:http://www.ytmp3.cn/down/57799.mp3

不要忘记在Manifest.xml里添加网络权限:

    

 

你可能感兴趣的:(Android)