How android implements MediaPlayer for long-time music playback

Source: Internet
Author: User

For a long time, music is stored in the memory of the mobile phone because of its large size, which occupies too much resources.

MediaPlayer can be used to play Audio, Video, and streaming media. MediaPlayer supports Audio and Video playback.

On the Android interface, both the Music and Video applications call MediaPlayer.

MediaPlayer is implemented at the underlying layer based on the OpenCore (PacketVideo) Library.

I. Basic Knowledge:

First, let's take a look at the MediaPlayer lifecycle:

Below are common MediaPlayer methods:

[Java]

Method description

MediaPlayer Constructor

Create creates a multimedia file to be played.

GetCurrentPosition: Get the current playback position

GetDuration get file time

GetVideoHeight: get the video height

Get the video width by getVideoWidth.

IsLooping loop playback?

Whether isPlaying is playing

Pause

Prepare preparation (synchronization)

PrepareAsync preparation (asynchronous)

Release releases the MediaPlayer object

Reset MediaPlayer object

SeekTo specifies the playback position (in milliseconds)

SetAudioStreamType: Set the streaming media type

SetDataSource

SetDisplay settings use SurfaceHolder to display multimedia

SetLooping

SetOnButteringUpdateListener network streaming media buffer listener

SetOnErrorListener

SetOnVideoSizeChangedListener video size monitoring

SetScreenOnWhilePlaying: Set whether to use SurfaceHolder to keep the screen displayed.

SetVolume sets the volume

Start

Stop

Method description

MediaPlayer Constructor

Create creates a multimedia file to be played.

GetCurrentPosition: Get the current playback position

GetDuration get file time

GetVideoHeight: get the video height

Get the video width by getVideoWidth.

IsLooping loop playback?

Whether isPlaying is playing

Pause

Prepare preparation (synchronization)

PrepareAsync preparation (asynchronous)

Release releases the MediaPlayer object

Reset MediaPlayer object

SeekTo specifies the playback position (in milliseconds)

SetAudioStreamType: Set the streaming media type

SetDataSource

SetDisplay settings use SurfaceHolder to display multimedia

SetLooping

SetOnButteringUpdateListener network streaming media buffer listener

SetOnErrorListener

SetOnVideoSizeChangedListener video size monitoring

SetScreenOnWhilePlaying: Set whether to use SurfaceHolder to keep the screen displayed.

SetVolume sets the volume

Start

Stop

This figure and the names of these functions do not need to be too concerned for beginners. Just take a look at the basic terms and wait until there is a real Interaction Problem in the project.

We only need to understand the following lines of code (Steps for playing music using MediaPlayer in Android ):

[Java]

MediaPlayer mp = new MediaPlayer (); // construct a MediaPlayer object

Mp. setDataSource ("/sdcard/testcard"); // sets the file path

Mp. prepare (); // prepare

Mp. start (); // start playing

MediaPlayer mp = new MediaPlayer (); // construct a MediaPlayer object

Mp. setDataSource ("/sdcard/testcard"); // sets the file path

Mp. prepare (); // prepare

Mp. start (); // start playing

The above four lines of code enable media file playback. However, if you want to control the volume, the AudioMananger class is involved.

Common AudioManager methods are as follows:

A. Obtain the Sound Manager:

[Java]

AudioManager audioManager = (AudioManager) this. getSystemService (AUDIO_SERVICE );

AudioManager audioManager = (AudioManager) this. getSystemService (AUDIO_SERVICE );

B. Set the sound mode:

[Java]

// Sound mode

AudioManager. setRingerMode (AudioManager. RINGER_MODE_NORMAL );

// Mute mode

AudioManager. setRingerMode (AudioManager. RINGER_MODE_SILENT );

// Vibration Mode

AudioManager. setRingerMode (AudioManager. RINGER_MODE_VIBRATE );

// Sound mode

AudioManager. setRingerMode (AudioManager. RINGER_MODE_NORMAL );

// Mute mode

AudioManager. setRingerMode (AudioManager. RINGER_MODE_SILENT );

// Vibration Mode

AudioManager. setRingerMode (AudioManager. RINGER_MODE_VIBRATE );

C. Adjust the sound size:

[Java]

// Reduce the sound volume

AudioManager. adjustVolume (AudioManager. ADJUST_LOWER, 0 );

// Increase the sound volume

AudioManager. adjustVolume (AudioManager. ADJUST_RAISE, 0 );

// Reduce the sound volume

AudioManager. adjustVolume (AudioManager. ADJUST_LOWER, 0 );

// Increase the sound volume

AudioManager. adjustVolume (AudioManager. ADJUST_RAISE, 0 );

D. Obtain the volume:

[Java]

// Obtain the current volume of the Current Device

AudioManager. getStreamVolume (int streamType)

// Obtain the maximum volume of the Current Device

AudioManager. getStreamMaxVolume (int streamType)

// Obtain the current volume of the Current Device

AudioManager. getStreamVolume (int streamType)

// Obtain the maximum volume of the Current Device

AudioManager. getStreamMaxVolume (int streamType)

E. Others:

[Java]

GetMode () obtains the audio mode.

GetRingerMode ()

SetRingerMode (int ringerMode) changes the ringtone Mode

If the mode related to the mobile phone shake is used, remember to add the permission. Android. permission. VIBRATE!

GetMode () obtains the audio mode.

GetRingerMode ()

SetRingerMode (int ringerMode) changes the ringtone Mode

If the mode related to the mobile phone shake is used, remember to add the permission. Android. permission. VIBRATE!

Ii. Programming implementation:

1. Edit the interface (reslayoutmain. xml ):

[Java]

  

Android: orientation = "vertical"

Android: layout_width = "fill_parent"

Android: layout_height = "fill_parent"

>

  

Android: text = "playing music"

Android: id = "@ + id/ButtonPlay"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content">

  

  

Android: text = "pause music"

Android: id = "@ + id/ButtonPause"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content">

  

  

Android: text = "Stop music"

Android: id = "@ + id/ButtonStop"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content">

  

  

Android: text = "adding music"

Android: id = "@ + id/ButtonVAdd"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content">

  

  

Android: text = "Reducing music"

Android: id = "@ + id/ButtonVReduce"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content">

  

  

  

Android: orientation = "vertical"

Android: layout_width = "fill_parent"

Android: layout_height = "fill_parent"

>

  

Android: text = "playing music"

Android: id = "@ + id/ButtonPlay"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content">

  

  

Android: text = "pause music"

Android: id = "@ + id/ButtonPause"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content">

  

  

Android: text = "Stop music"

Android: id = "@ + id/ButtonStop"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content">

  

  

Android: text = "adding music"

Android: id = "@ + id/ButtonVAdd"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content">

  

  

Android: text = "Reducing music"

Android: id = "@ + id/ButtonVReduce"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content">

  

  

The interface layout is as follows:

2. code editing (srcwyfzclMyActivity. java ):

[Java]

Package wyf. zcl;

Import android. app. Activity; // introduce related packages

Import android. media. AudioManager; // introduce related packages

Import android. media. MediaPlayer; // introduce related packages

Import android. OS. Bundle; // introduce related packages

Import android. view. View; // introduce related packages

Import android. widget. Button; // introduce related packages

Import android. widget. Toast;

Public class MyActivity extends Activity {

/** Called when the activity is first created .*/

Private Button bPlay; // The playback Button.

Private Button bPause; // the pause Button.

Private Button bStop; // the stop Button.

Private Button bAdd; // increase the volume

Private Button bReduce; // reduce the volume

Private boolean pauseFlag = false; // The flag is paused. The value true indicates that the flag is paused. The value false indicates that the flag is not paused.

MediaPlayer mp; // MediaPlayer reference

AudioManager am; // AudioManager reference

@ Override

Public void onCreate (Bundle savedInstanceState) {// called during Activity Creation

Super. onCreate (savedInstanceState );

SetContentView (R. layout. main); // sets the display content of the Activity.

BPlay = (Button) findViewById (R. id. ButtonPlay); // instantiate the playback Button

BPause = (Button) findViewById (R. id. ButtonPause); // instantiate the pause Button

BStop = (Button) findViewById (R. id. ButtonStop); // instantiate the stop Button

BAdd = (Button) findViewById (R. id. ButtonVAdd); // instantiate the volume increase Button

BReduce = (Button) findViewById (R. id. ButtonVReduce); // instantiate the volume reduction Button

Mp = new MediaPlayer ();

Am = (AudioManager) this. getSystemService (this. AUDIO_SERVICE );

BPlay. setOnClickListener (new View. OnClickListener () {// listener of the playback button

@ Override

Public void onClick (View v ){

Try {

Mp. setDataSource ("/sdcard/music/sound_of_dream_djcard"); // load the audio and enter the Initialized status.

} Catch (Exception e) {e. printStackTrace ();}

Try {

Mp. prepare (); // enter the prepared status.

} Catch (Exception e) {e. printStackTrace ();}

Mp. start (); // play music

Toast. makeText (MyActivity. this, "Play Music", Toast. LENGTH_SHORT). show ();

}});

BPause. setOnClickListener (new View. OnClickListener () {// pause button to add listener

@ Override

Public void onClick (View v ){

If (mp. isPlaying () {// if it is in the playing State

Mp. pause (); // call the pause Method

PauseFlag = true; // sets the pause flag.

} Else if (pauseFlag ){

Mp. start (); // play music

PauseFlag = false; // set the pause flag.

Toast. makeText (MyActivity. this, "pause playback", Toast. LENGTH_SHORT). show ();

}}

});

BStop. setOnClickListener (new View. OnClickListener () {// stop button to add listener

@ Override

Public void onClick (View v ){

Mp. stop (); // stop playing

Mp. reset (); // reset the status to the uninitialized state.

Try {

Mp. setDataSource ("/sdcard/music/sound_of_dream_djcard"); // load the audio and enter the Initialized status.

} Catch (Exception e) {e. printStackTrace ();}

Try {

Mp. prepare (); // enter the prepared status.

} Catch (Exception e) {e. printStackTrace ();}

Toast. makeText (MyActivity. this, "Stop playing", Toast. LENGTH_SHORT). show ();

}});

BAdd. setOnClickListener (new View. OnClickListener () {// click the volume increase button to add a listener.

@ Override

Public void onClick (View v ){

Am. adjustVolume (AudioManager. ADJUST_RAISE, 0); // increase the volume

System. out. println ("faaa ");

Toast. makeText (MyActivity. this, "increase volume", Toast. LENGTH_SHORT). show ();

}});

BReduce. setOnClickListener (new View. OnClickListener () {// Add listener with the volume reduction button

@ Override

Public void onClick (View v ){

Am. adjustVolume (AudioManager. ADJUST_LOWER, 0); // reduce the volume

Toast. makeText (MyActivity. this, "", Toast. LENGTH_SHORT). show ();

}});

}

}

Package wyf. zcl;

Import android. app. Activity; // introduce related packages

Import android. media. AudioManager; // introduce related packages

Import android. media. MediaPlayer; // introduce related packages

Import android. OS. Bundle; // introduce related packages

Import android. view. View; // introduce related packages

Import android. widget. Button; // introduce related packages

Import android. widget. Toast;

Public class MyActivity extends Activity {

/** Called when the activity is first created .*/

Private Button bPlay; // The playback Button.

Private Button bPause; // the pause Button.

Private Button bStop; // the stop Button.

Private Button bAdd; // increase the volume

Private Button bReduce; // reduce the volume

Private boolean pauseFlag = false; // The flag is paused. The value true indicates that the flag is paused. The value false indicates that the flag is not paused.

MediaPlayer mp; // MediaPlayer reference

AudioManager am; // AudioManager reference

@ Override

Public void onCreate (Bundle savedInstanceState) {// called during Activity Creation

Super. onCreate (savedInstanceState );

SetContentView (R. layout. main); // sets the display content of the Activity.

BPlay = (Button) findViewById (R. id. ButtonPlay); // instantiate the playback Button

BPause = (Button) findViewById (R. id. ButtonPause); // instantiate the pause Button

BStop = (Button) findViewById (R. id. ButtonStop); // instantiate the stop Button

BAdd = (Button) findViewById (R. id. ButtonVAdd); // instantiate the volume increase Button

BReduce = (Button) findViewById (R. id. ButtonVReduce); // instantiate the volume reduction Button

Mp = new MediaPlayer ();

Am = (AudioManager) this. getSystemService (this. AUDIO_SERVICE );

BPlay. setOnClickListener (new View. OnClickListener () {// listener of the playback button

@ Override

Public void onClick (View v ){

Try {

Mp. setDataSource ("/sdcard/music/sound_of_dream_djcard"); // load the audio and enter the Initialized status.

} Catch (Exception e) {e. printStackTrace ();}

Try {

Mp. prepare (); // enter the prepared status.

} Catch (Exception e) {e. printStackTrace ();}

Mp. start (); // play music

Toast. makeText (MyActivity. this, "Play Music", Toast. LENGTH_SHORT). show ();

}});

BPause. setOnClickListener (new View. OnClickListener () {// pause button to add listener

@ Override

Public void onClick (View v ){

If (mp. isPlaying () {// if it is in the playing State

Mp. pause (); // call the pause Method

PauseFlag = true; // sets the pause flag.

} Else if (pauseFlag ){

Mp. start (); // play music

PauseFlag = false; // set the pause flag.

Toast. makeText (MyActivity. this, "pause playback", Toast. LENGTH_SHORT). show ();

}}

});

BStop. setOnClickListener (new View. OnClickListener () {// stop button to add listener

@ Override

Public void onClick (View v ){

Mp. stop (); // stop playing

Mp. reset (); // reset the status to the uninitialized state.

Try {

Mp. setDataSource ("/sdcard/music/sound_of_dream_djcard"); // load the audio and enter the Initialized status.

} Catch (Exception e) {e. printStackTrace ();}

Try {

Mp. prepare (); // enter the prepared status.

} Catch (Exception e) {e. printStackTrace ();}

Toast. makeText (MyActivity. this, "Stop playing", Toast. LENGTH_SHORT). show ();

}});

BAdd. setOnClickListener (new View. OnClickListener () {// click the volume increase button to add a listener.

@ Override

Public void onClick (View v ){

Am. adjustVolume (AudioManager. ADJUST_RAISE, 0); // increase the volume

System. out. println ("faaa ");

Toast. makeText (MyActivity. this, "increase volume", Toast. LENGTH_SHORT). show ();

}});

BReduce. setOnClickListener (new View. OnClickListener () {// Add listener with the volume reduction button

@ Override

Public void onClick (View v ){

Am. adjustVolume (AudioManager. ADJUST_LOWER, 0); // reduce the volume

Toast. makeText (MyActivity. this, "", Toast. LENGTH_SHORT). show ();

}});

}

}

The "/sdcard/music/sound_of_dream_DJ.mp3" file on the SD card is played.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.