Playing MP3 in Android is very simple and often used in projects, such as background music for projects and prompts for certain functions in applications. It is widely used. Here is a simple example:
Layout file Configuration:
<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: layout_width = "wrap_content" Android: Orientation = "vertical" Android: layout_height = "wrap_content"> <button Android: TEXT = "play" Android: Id = "@ + ID/btnstart" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"> </button> <button Android: TEXT = "stop" Android: Id = "@ + ID/btnstop" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"> </button> </linearlayout>
Java implementation file:
/*****/Package COM. demo. media; import android. app. activity; import android. media. mediaplayer; import android. OS. bundle; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import COM. demo. helloworld. r;/*** @ author XSL * vaiyanzi@gmail.com * MP3 playback function */public class mediademo extends activity {private button btnstart, btnstop; Private Static mediaplayer mediapl Ayer = NULL; @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. media); btnstart = (button) This. findviewbyid (R. id. btnstart); btnstart. setonclicklistener (New buttonlistener (); btnstop = (button) This. findviewbyid (R. id. btnstop); btnstop. setonclicklistener (New buttonlistener ();} class buttonlistener implements onclicklistener {public void on Click (view v) {Switch (v. GETID () {case R. id. btnstart: If (mediaplayer = NULL) {// create a playback instance mediaplayer = mediaplayer. create (mediademo. this, R. raw. tishiyin);} Try {// set whether to play mediaplayer cyclically. setlooping (true); // sets the playing Start Point mediaplayer. seekto (0); // start playing mediaplayer. start ();} catch (illegalstateexception e) {e. printstacktrace ();} catch (exception e) {e. printstacktrace ();} break; case R. id. btnstop: If (mediaplayer! = NULL) {// stop playing mediaplayer. Stop (); // release the resource mediaplayer. Release (); mediaplayer = NULL;} break ;}}}}
Effect