Android basic tutorial-9.2 MediaPlayer playing audio and video
This section introduces:
This section introduces MediaPlayer in Android multimedia. We can use this API to play audio and video.
This class is an important component in the Androd Multimedia Framework. Through this class, we can obtain and decode it in the smallest step.
And play audio and video. It supports three different media sources:
The URI inside the local resource. For example, you can use ContentResolver to obtain the external URL (Stream)
List of media formats supported by Android
For the list of Media Formats Supported by Android, see the Supported Media Formats document.
In this section, we will use MediaPlayer to write a simple example of playing audio and video!
Official API documentation: MediaPlayer
1. Detailed description of relevant methods 1) obtain the MediaPlayer instance:
YesDirect newOr callCreateMethod creation:
MediaPlayer mp = new MediaPlayer (); MediaPlayer mp = MediaPlayer. create (this, R. raw. test); // No need to call setDataSource
In addition, create has the following form:
Create (Context context, Uri uri, SurfaceHolder holder)
Create a multimedia player using Uri and the specified SurfaceHolder [abstract class]
2) set the playback file:
// ① Raw Resource: MediaPlayer. create (this, R. raw. test); // ② local file path: mp. setDataSource (/sdcard/testcard); // ③ network URL File: mp. setDataSource (http://www.xxx.com/music/test.mp3 );
In addition, the setDataSource () method has multiple parameters of the following type: FileDescriptor.
When using APIs, you need to put the files in the assets folder of the res folder, and then use the following code to set DataSource:
AssetFileDescriptor fileDescriptor = getAssets().openFd(rain.mp3);m_mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),fileDescriptor.getStartOffset(), fileDescriptor.getLength());
3) Other methods
GetCurrentPosition(): Obtain the current playback position.
GetDuration(): Get the file time
GetVideoHeight(): Get the video height.
GetVideoWidth(): Get the video width.
IsLooping(): Whether to play cyclically
IsPlaying(): Whether the video is being played
Pause(): Pause
Prepare(): Prepare (synchronize)
PrepareAsync(): Prepare (asynchronous)
Release (): Release the MediaPlayer object.
Reset(): Resets the MediaPlayer object.
SeekTo (int msec): Specifies the playback position (in milliseconds)
SetAudioStreamType (int streamtype): Specifies the streaming media type.
SetDisplay (SurfaceHolder sh): Set SurfaceHolder to display multimedia
SetLooping (boolean looping): Set whether to play cyclically.
SetOnBufferingUpdateListener (MediaPlayer. OnBufferingUpdateListener listener):
Network streaming media buffer listener
SetOnCompletionListener (MediaPlayer. OnCompletionListener listener):
Network Streaming Media Playback End monitoring
SetOnErrorListener (MediaPlayer. OnErrorListener listener):
Set error message listener
SetOnVideoSizeChangedListener (MediaPlayer. OnVideoSizeChangedListener listener):
Video size monitoring
SetScreenOnWhilePlaying (boolean screenOn): Set whether to display with SurfaceHolder
SetVolume (float leftVolume, float rightVolume): Set the volume
Start(): Start playing
Stop(): Stops playing.
2. Sample Code
Example 1: Use MediaPlayer to play audio:
Run:
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; // indicates whether the MediaPlayer is released. @ 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 (); // start playing btn_play.setEnabled (false); btn_pause.setEnabled (true); btn_stop.setEnabled (true); break; case R. id. btn_pause: mPlayer. pause (); // stop playing btn_play.setEnabled (true); btn_pause.setEnabled (false); btn_stop.setEnabled (false); break; case R. id. btn_stop: mPlayer. reset (); // reset MediaPlayer mPlayer. release (); // release MediaPlayer isRelease = true; btn_play.setEnabled (true); btn_pause.setEnabled (false); btn_stop.setEnabled (false); break ;}}}
Note:
The audio file in the res/raw directory is played, and the create method is called when the MediaPlayer is created.
You do not need to call prepare () any more. If the constructor is used for Constructor construction, you need to call the prepare () method once!
In addition, paste the sample code for playing audio in two other ways in the official document:
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 use a URL to play an online audio file in the form of a stream, this file must be available
Progressive download
Example 2: Use MediaPlayer to play a video
MediaPlayer is mainly used to play audio and does not provide an image output interface. Therefore, we need to use other
To display the image output played by MediaPlayer.SurfaceView
The following example shows how to use SurfaceView to play a video:
Run:
Implementation Code:
Layout file:Activity_main.xml
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 success; private Button btn_stop; @ Override protected void onCreate (Bundle success) {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); listener (this); initialize (this); // initialize the SurfaceHolder class, SurfaceView controller surfaceHolder = sfv_show.getHolder (); surfaceHolder. addCallback (this); surfaceHolder. setFixedSize (320,220); // display resolution, not set to video default} @ 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); // sets the display video to be displayed on 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. There is a SurfaceView layout, and then call getHolder to obtain a SurfaceHolder object,
Complete SurfaceView settings and set the display resolution and a Callback interface,
The three methods of SurfaceView creation, change, and destruction are overwritten! Then click to control the playback
And paused ~
Example 3: Use VideoView to play a video
In addition to using MediaPlayer + SurfaceView to play a video, we can also use VideoView to directly
Play a video. You can play the video with a few changes! The running effect is the same as the above, so you will not post it,
Code directly!
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);} // read the file stored in the raw directory // 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 will not be explained ~ If you have any questions, run your next Demo ~