Android intermediate tutorial ------ playing mp3 with Android MediaPlayer

Source: Internet
Author: User

MediaPlayer is implemented at the underlying layer based on the OpenCore (PacketVideo) Library. To build a MediaPlayer program, the upper layer also contains inter-process communication and other content, the basis for inter-process communication is the Binder Mechanism in the basic Android library.
In today's example, we only use MediaPlayer to play a beautiful English brother love foolton In the res/raw folder. The program has three ImageButton buttons, play, stop, and pause! I don't need to talk about the functions of the three buttons. Next I will show you how to implement this Demo By Step.
Step 1: Create an Android project named MediaPlayerDemo.
Step 2: import the play.png, pause.png, and stop.png files to the res/drawable folder.
Step 3: design the UI layout and put three ImageButton in main. xml (here we can use AbsoluteLayout or RelativeLayout, I will use the latter). The Code is as follows:

[Html]
<SPAN style = "COLOR: # cc6600; FONT-SIZE: 12px"> <? Xml version = "1.0" encoding = "UTF-8"?>
<RelativeLayout
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
Android: background = "@ drawable/white"
Xmlns: android = "http://schemas.android.com/apk/res/android"
>
<TextView
Android: id = "@ + id/myTextView1"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = "@ string/hello"
Android: layout_alignParentTop = "true"
Android: layout_alignParentLeft = "true"
>
</TextView>
<ImageButton
Android: id = "@ + id/myButton1"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: src = "@ drawable/play"
Android: layout_below = "@ + id/myTextView1"
>
</ImageButton>
<ImageButton
Android: id = "@ + id/myButton3"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: src = "@ drawable/pause"
Android: layout_alignTop = "@ + id/myButton1"
Android: layout_toRightOf = "@ + id/myButton1"
>
</ImageButton>
<ImageButton
Android: id = "@ + id/myButton2"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: src = "@ drawable/stop"
Android: layout_alignTop = "@ + id/myButton1"
Android: layout_toRightOf = "@ + id/myButton3"
>
</ImageButton>
</RelativeLayout>
</SPAN>

<? Xml version = "1.0" encoding = "UTF-8"?>
<RelativeLayout
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
Android: background = "@ drawable/white"
Xmlns: android = "http://schemas.android.com/apk/res/android"
>
<TextView
Android: id = "@ + id/myTextView1"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = "@ string/hello"
Android: layout_alignParentTop = "true"
Android: layout_alignParentLeft = "true"
>
</TextView>
<ImageButton
Android: id = "@ + id/myButton1"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: src = "@ drawable/play"
Android: layout_below = "@ + id/myTextView1"
>
</ImageButton>
<ImageButton
Android: id = "@ + id/myButton3"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: src = "@ drawable/pause"
Android: layout_alignTop = "@ + id/myButton1"
Android: layout_toRightOf = "@ + id/myButton1"
>
</ImageButton>
<ImageButton
Android: id = "@ + id/myButton2"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: src = "@ drawable/stop"
Android: layout_alignTop = "@ + id/myButton1"
Android: layout_toRightOf = "@ + id/myButton3"
>
</ImageButton>
</RelativeLayout>

 


Step 4: implement the main control program MediaPlayerDemo. java. The Code is as follows:

[Java] view plaincopyprint?
<SPAN style = "COLOR: # cc6600; FONT-SIZE: 12px"> package com. android. test;
Import android. app. Activity;
Import android. media. MediaPlayer;
Import android. OS. Bundle;
Import android. view. View;
Import android. widget. ImageButton;
Import android. widget. TextView;
Public class MediaPlayerDemo extends Activity {
Private ImageButton mb1, mb2, mb3;
Private TextView TV;
Private MediaPlayer mp;
// Declare a variable to determine whether it is paused. The default value is false.
Private boolean isPaused = false;
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
// Find the resource through findViewById
Mb1 = (ImageButton) findViewById (R. id. myButton1 );
Mb2 = (ImageButton) findViewById (R. id. myButton2 );
Mb3 = (ImageButton) findViewById (R. id. myButton3 );
TV = (TextView) findViewById (R. id. myTextView1 );
// Create a mediaplayerobject to folder the lovefool.pdf
Mp = MediaPlayer. create (this, R. raw. lovefool );
// Adds a music play button event.
Mb1.setOnClickListener (new ImageButton. OnClickListener (){
@ Override
Public void onClick (View v ){
Try {
If (mp! = Null)
{
Mp. stop ();
}
Mp. prepare ();
Mp. start ();
TV. setText ("playing music ...");
} Catch (Exception e ){
TV. setText ("an exception occurred during playback ...");
E. printStackTrace ();
}
}
});
Mb2.setOnClickListener (new ImageButton. OnClickListener (){
@ Override
Public void onClick (View v ){
Try {
If (mp! = Null)
{
Mp. stop ();
TV. setText ("Stop playing music ...");
}
} Catch (Exception e ){
TV. setText ("an exception occurred when music stops ...");
E. printStackTrace ();
}
}
});
Mb3.setOnClickListener (new ImageButton. OnClickListener (){
@ Override
Public void onClick (View v ){
Try {
If (mp! = Null)
{
If (isPaused = false)
{
Mp. pause ();
IsPaused = true;
TV. setText ("Stop playing! ");
}
Else if (isPaused = true)
{
Mp. start ();
IsPaused = false;
TV. setText ("start broadcasting! ");
}
}
} Catch (Exception e ){
TV. setText ("an exception occurred ...");
E. printStackTrace ();
}
}
});
/* When MediaPlayer. OnCompletionLister runs the Listener */
Mp. setOnCompletionListener (
New MediaPlayer. OnCompletionListener ()
{
// @ Override
/* Overwrite file broadcast completion event */
Public void onCompletion (MediaPlayer arg0)
{
Try
{
/* Unassign values between resources and MediaPlayer.
* Allow resources to be used by other programs */
Mp. release ();
/* Change TextView to end playback */
TV. setText ("music broadcasting ends! ");
}
Catch (Exception e)
{
TV. setText (e. toString ());
E. printStackTrace ();
}
}
});
/* When MediaPlayer. OnErrorListener runs the Listener */
Mp. setOnErrorListener (new MediaPlayer. OnErrorListener ()
{
@ Override
/* Overwrite the error handling event */
Public boolean onError (MediaPlayer arg0, int arg1, int arg2)
{
// TODO Auto-generated method stub
Try
{
/* Release the resource and MediaPlayer assignment when an error occurs */
Mp. release ();
TV. setText ("an exception occurred during playback! ");
}
Catch (Exception e)
{
TV. setText (e. toString ());
E. printStackTrace ();
}
Return false;
}
});
}
}
</SPAN>

Package com. android. test;
Import android. app. Activity;
Import android. media. MediaPlayer;
Import android. OS. Bundle;
Import android. view. View;
Import android. widget. ImageButton;
Import android. widget. TextView;
Public class MediaPlayerDemo extends Activity {
Private ImageButton mb1, mb2, mb3;
Private TextView TV;
Private MediaPlayer mp;
// Declare a variable to determine whether it is paused. The default value is false.
Private boolean isPaused = false;
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
// Find the resource through findViewById
Mb1 = (ImageButton) findViewById (R. id. myButton1 );
Mb2 = (ImageButton) findViewById (R. id. myButton2 );
Mb3 = (ImageButton) findViewById (R. id. myButton3 );
TV = (TextView) findViewById (R. id. myTextView1 );
// Create a mediaplayerobject to folder the lovefool.pdf
Mp = MediaPlayer. create (this, R. raw. lovefool );
// Adds a music play button event.
Mb1.setOnClickListener (new ImageButton. OnClickListener (){
@ Override
Public void onClick (View v ){
Try {
If (mp! = Null)
{
Mp. stop ();
}
Mp. prepare ();
Mp. start ();
TV. setText ("playing music ...");
} Catch (Exception e ){
TV. setText ("an exception occurred during playback ...");
E. printStackTrace ();
}
}
});
Mb2.setOnClickListener (new ImageButton. OnClickListener (){
@ Override
Public void onClick (View v ){
Try {
If (mp! = Null)
{
Mp. stop ();
TV. setText ("Stop playing music ...");
}
} Catch (Exception e ){
TV. setText ("an exception occurred when music stops ...");
E. printStackTrace ();
}
}
});
Mb3.setOnClickListener (new ImageButton. OnClickListener (){
@ Override
Public void onClick (View v ){
Try {
If (mp! = Null)
{
If (isPaused = false)
{
Mp. pause ();
IsPaused = true;
TV. setText ("Stop playing! ");
}
Else if (isPaused = true)
{
Mp. start ();
IsPaused = false;
TV. setText ("start broadcasting! ");
}
}
} Catch (Exception e ){
TV. setText ("an exception occurred ...");
E. printStackTrace ();
}
}
});
/* When MediaPlayer. OnCompletionLister runs the Listener */
Mp. setOnCompletionListener (
New MediaPlayer. OnCompletionListener ()
{
// @ Override
/* Overwrite file broadcast completion event */
Public void onCompletion (MediaPlayer arg0)
{
Try
{
/* Unassign values between resources and MediaPlayer.
* Allow resources to be used by other programs */
Mp. release ();
/* Change TextView to end playback */
TV. setText ("music broadcasting ends! ");
}
Catch (Exception e)
{
TV. setText (e. toString ());
E. printStackTrace ();
}
}
});
/* When MediaPlayer. OnErrorListener runs the Listener */
Mp. setOnErrorListener (new MediaPlayer. OnErrorListener ()
{
@ Override
/* Overwrite the error handling event */
Public boolean onError (MediaPlayer arg0, int arg1, int arg2)
{
// TODO Auto-generated method stub
Try
{
/* Release the resource and MediaPlayer assignment when an error occurs */
Mp. release ();
TV. setText ("an exception occurred during playback! ");
}
Catch (Exception e)
{
TV. setText (e. toString ());
E. printStackTrace ();
}
Return false;
}
});
}
}

 

 


Step 5: The running effect is as follows. A beautiful love fool is playing... enjoy...

 

Diffusion learning:
If we want to play the music in the mobile phone card or download the streaming media from the URL, the Programme is as follows:

[Java]
<SPAN style = "COLOR: # cc6600; FONT-SIZE: 12px"> MediaPlayer mp = new MediaPlayer ();
Mp. setDataSource (String URL/FILE_PATH );
Mp. prepare ();
Mp. start (); </SPAN>

MediaPlayer mp = new MediaPlayer ();
Mp. setDataSource (String URL/FILE_PATH );
Mp. prepare ();
Mp. start ();

 

 


The preceding procedure uses the MediaPlayer. setDataSource () method to pass the URL or file path as a string. When using the setDataSource () method, pay attention to the following three points:
1. The constructed MediaPlayer must implement a Null check on the image.
2. exceptions such as IllegalArgumentException and IOException must be received. In many cases, the files you use do not exist.
3. If you use a URL to play an online media file, the file must support pragressive download.

Related Article

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.