MediaPlayer plays audio and video
Introduction to this section:
This section brings about MediaPlayer in Android multimedia. We can play audio and video through this API. This class is an important component in the Androd multimedia framework. Through this class, we can obtain and decode in the smallest steps. and play audio and video. It supports three different media sources:
- Local resources
- Internal URI, for example, you can get
- external URL (stream) through ContentResolver For the list of media formats supported by Android
For the list of media formats supported by Android, see:Supported Media Formats Document
We will use this section MediaPlayer to write a simple example of playing audio and video!
Official API document: MediaPlayer
1. Detailed explanation of related methods
1) Obtain MediaPlayer instance:
You can direct new or call the create method to create:
MediaPlayer mp = new MediaPlayer(); MediaPlayer mp = MediaPlayer.create(this, R.raw.test); //无需再调用setDataSource
In addition, create also has this form: create(Context context, Uri uri, SurfaceHolder holder)Create a multimedia player through Uri and specify SurfaceHolder [Abstract class]
2) Set the playback file:
//①raw下的资源: MediaPlayer.create(this, R.raw.test); //②本地文件路径: mp.setDataSource("/sdcard/test.mp3"); //③网络URL文件: mp.setDataSource("http://www.xxx.com/music/test.mp3");
Also setDataSource( ) method, which contains such a type of parameter: FileDescriptor, when using this When using the API, you need to put the file into the assets folder at the same level as the res folder, and then use the following code to set the DataSource:
AssetFileDescriptor fileDescriptor = getAssets().openFd("rain.mp3"); m_mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),fileDescriptor.getStartOffset(), fileDescriptor.getLength());
3) Other methods
- getCurrentPosition( ): Get the current playback position
- getDuration(): Get the time of the file
- getVideoHeight(): Get the video height
- getVideoWidth(): Get the video width
- isLooping(): Whether to loop and play
- isPlaying(): Whether to play
- pause (): Pause
- prepare(): Prepare (synchronous)
- prepareAsync(): Prepare (asynchronous)
- release(): Release the MediaPlayer object
- reset(): Reset the MediaPlayer object
- seekTo(int msec) : Specify the playback position (time in milliseconds)
- setAudioStreamType(int streamtype) : Specify the type of streaming media
- setDisplay(SurfaceHolder sh) : Set up SurfaceHolder to display multimedia
- setLooping(boolean looping): Set whether to loop playback
- ##setOnBufferingUpdateListener(MediaPlayer.OnBufferingUpdateListener listener): Buffer listening for network streaming media
- setOnCompletionListener(MediaPlayer.OnCompletionListener listener): Network streaming media playback end listening
- setOnErrorListener(MediaPlayer.OnErrorListener listener): Set error message listener
- setOnVideoSizeChangedListener(MediaPlayer.OnVideoSizeChangedListener listener): Video size monitoring
- setScreenOnWhilePlaying(boolean screenOn): Set whether to use SurfaceHolder to display
- setVolume(float leftVolume, float rightVolume): Set the volume
- start(): Start playing
- stop(): Stop playing
2. Use code examples
Example 1: Use MediaPlayer to play audio:
Running renderings:
Key code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private Button btn_play; private Button btn_pause; private Button btn_stop; private MediaPlayer mPlayer = null; private boolean isRelease = true; //判断是否MediaPlayer是否释放的标志 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bindViews(); } private void bindViews() { btn_play = (Button) findViewById(R.id.btn_play); btn_pause = (Button) findViewById(R.id.btn_pause); btn_stop = (Button) findViewById(R.id.btn_stop); btn_play.setOnClickListener(this); btn_pause.setOnClickListener(this); btn_stop.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btn_play: if(isRelease){ mPlayer = MediaPlayer.create(this,R.raw.fly); isRelease = false; } mPlayer.start(); //开始播放 btn_play.setEnabled(false); btn_pause.setEnabled(true); btn_stop.setEnabled(true); break; case R.id.btn_pause: mPlayer.pause(); //停止播放 btn_play.setEnabled(true); btn_pause.setEnabled(false); btn_stop.setEnabled(false); break; case R.id.btn_stop: mPlayer.reset(); //重置MediaPlayer mPlayer.release(); //释放MediaPlayer isRelease = true; btn_play.setEnabled(true); btn_pause.setEnabled(false); btn_stop.setEnabled(false); break; } } }Note:
is playing the audio file in the res/raw directory, creating the MediaPlayer call It is the create method, before starting playback for the first time There is no need to call prepare() again. If it is constructed using the constructor method, you need to call the prepare() method once! In addition, post the sample code for playing audio from the other two channels in the official documentation:
Local Uri:
Uri myUri = ....; // initialize Uri here MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setDataSource(getApplicationContext(), myUri); mediaPlayer.prepare(); mediaPlayer.start();
External 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();
Note: If you stream an online audio file through a URL, the file must be Progressive Download
Example 2: Use MediaPlayer to play video
MediaPlayer is mainly used to play audio and does not provide an image output interface, so we need to use other Component to display the image output played by MediaPlayer, we can use SurfaceView to display it. Below we use SurfaceView to write an example of video playback:
Running renderings :
Implementation code:
Layout file:activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="5dp"> <SurfaceView android:id="@+id/sfv_show" android:layout_width="match_parent" android:layout_height="300dp" /> <Button android:id="@+id/btn_start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="开始" /> <Button android:id="@+id/btn_pause" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="暂停 " /> <Button android:id="@+id/btn_stop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="终止" /> </LinearLayout>
MainActivity.java:
public class MainActivity extends AppCompatActivity implements View.OnClickListener, SurfaceHolder.Callback { private MediaPlayer mPlayer = null; private SurfaceView sfv_show; private SurfaceHolder surfaceHolder; private Button btn_start; private Button btn_pause; private Button btn_stop; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bindViews(); } private void bindViews() { sfv_show = (SurfaceView) findViewById(R.id.sfv_show); btn_start = (Button) findViewById(R.id.btn_start); btn_pause = (Button) findViewById(R.id.btn_pause); btn_stop = (Button) findViewById(R.id.btn_stop); btn_start.setOnClickListener(this); btn_pause.setOnClickListener(this); btn_stop.setOnClickListener(this); //初始化SurfaceHolder类,SurfaceView的控制器 surfaceHolder = sfv_show.getHolder(); surfaceHolder.addCallback(this); surfaceHolder.setFixedSize(320, 220); //显示的分辨率,不设置为视频默认 } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_start: mPlayer.start(); break; case R.id.btn_pause: mPlayer.pause(); break; case R.id.btn_stop: mPlayer.stop(); break; } } @Override public void surfaceCreated(SurfaceHolder holder) { mPlayer = MediaPlayer.create(MainActivity.this, R.raw.lesson); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mPlayer.setDisplay(surfaceHolder); //设置显示视频显示在SurfaceView上 } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} @Override public void surfaceDestroyed(SurfaceHolder holder) {} @Override protected void onDestroy() { super.onDestroy(); if (mPlayer.isPlaying()) { mPlayer.stop(); } mPlayer.release(); } }
The code is very simple. The layout has a SurfaceView, and then calls getHolder to obtain a SurfaceHolder object. Complete the SurfaceView related settings here, set the display resolution and a Callback interface. Overriding the three methods of SurfaceView when it is created, when it changes, and when it is destroyed! Then button controls playback And just pause~
Example 3: Use VideoView to play videos
In addition to using MediaPlayer + SurfaceView to play videos, we can also use VideoView to directly To play the video, we can achieve video playback by changing a little bit! The operating effect is consistent with the above, so I won’t post it. Just go to the code!
MainActivity.java:
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private VideoView videoView; private Button btn_start; private Button btn_pause; private Button btn_stop; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bindViews(); } private void bindViews() { videoView = (VideoView) findViewById(R.id.videoView); btn_start = (Button) findViewById(R.id.btn_start); btn_pause = (Button) findViewById(R.id.btn_pause); btn_stop = (Button) findViewById(R.id.btn_stop); btn_start.setOnClickListener(this); btn_pause.setOnClickListener(this); btn_stop.setOnClickListener(this); //根据文件路径播放 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { videoView.setVideoPath(Environment.getExternalStorageDirectory() + "/lesson.mp4"); } //读取放在raw目录下的文件 //videoView.setVideoURI(Uri.parse("android.resource://com.jay.videoviewdemo/" + R.raw.lesson)); videoView.setMediaController(new MediaController(this)); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_start: videoView.start(); break; case R.id.btn_pause: videoView.pause(); break; case R.id.btn_stop: videoView.stopPlayback(); break; } } }
The code is very simple and I won’t explain it~ If you have any questions, just run the next Demo~
3. Download the sample code for this section:
Summary of this section:
Okay, this section briefly introduces how to use MediaPlayer to play audio and combine it with SurfaceView to play videos. Finally, I wrote an example of using VideoView to play videos. They are all very simple usage~ I believe it is very easy for everyone to learn~ Well, thank you~