基本创作和演奏

MediaPlayer 类可用于控制音频/视频文件和流的播放。

MediaPlayer 对象的创建可以有三种类型:

  1. 来自本地资源的媒体

    MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.resource);
    mediaPlayer.start(); // no need to call prepare(); create() does that for you
    
  2. 从本地 URI(从 ContentResolver 获取)

    Uri myUri = ....; // initialize Uri here
    MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setDataSource(getApplicationContext(), myUri);
    mediaPlayer.prepare();
    mediaPlayer.start();
    
  3. 来自外部 URL

    String url = "http://........"; // your URL here
    MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setDataSource(url);
    mediaPlayer.prepare(); // might take long! (for buffering, etc)
    mediaPlayer.start();