Android Getting Started notes-multimedia-MediaPlayer

Source: Internet
Author: User

Today we are going to write a super super simple player, using the android comes with the music player class MediaPlayer, the first one:

It only realizes the basic function of the player, the interface does not do, because it is not the focus of Kazakhstan.

Code:

1. Layout/activty_main.xml

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:orien tation= "Vertical" tools:context= ". Mainactivity "> <linearlayout android:layout_width=" match_parent "android:layout_height=" Wrap_conte NT "android:orientation=" horizontal "> <button android:id=" @+id/btn_pre "Android : layout_width= "wrap_content" android:layout_height= "wrap_content" android:text= "Pre"/> &l T Button android:id= "@+id/btn_stop" android:layout_width= "Wrap_content" Android:layout_heig            ht= "Wrap_content" android:text= "Stop"/> <button android:id= "@+id/btn_pause"          Android:layout_width= "Wrap_content" android:layout_height= "wrap_content"/> <button  Android:id= "@+id/btn_play" android:layout_width= "wrap_content" android:layout_height= "wrap_content "android:text=" Play "/> <button android:id=" @+id/btn_next "Android:layout_w Idth= "Wrap_content" android:layout_height= "Wrap_content" android:text= "Next"/> </linearlay        out> <linearlayout android:layout_width= "match_parent" android:layout_height= "Match_parent" android:orientation= "vertical" > <listview android:id= "@+id/music_listview" Android:lay Out_width= "Match_parent" android:layout_height= "wrap_content" > </ListView> </linearlayou T></linearlayout>

2. Mainactivity.java:

Package Com.example.ch7_01_mediaplayer;import Java.io.file;import Java.io.filenamefilter;import Java.io.ioexception;import Java.util.arraylist;import Java.util.list;import Android.media.mediaplayer;import Android.os.bundle;import Android.app.activity;import Android.content.context;import Android.view.Menu;import Android.view.view;import Android.widget.adapterview;import Android.widget.arrayadapter;import Android.widget.button;import Android.widget.listview;public class Mainactivity extends Activity {private Context Mcontext = this;private static final String music_path = new String ("/sdcard/");p rivate list<string> mmusiclist = NE W arraylist<string> ();p rivate ListView mmusiclistview;private int mcurrentmusicitem = 0;private MediaPlayer Mmediaplayer = null;private Button mbtnstop = null;private button Mbtnpause = null;private button Mbtnplay = null;private Button Mbtnnext = null;private button mbtnpre = null; @Overrideprotected void OnCreate (Bundle savedinstancestate) {SUPER.ONcreate (savedinstancestate); Setcontentview (r.layout.activity_main); mmediaplayer = new MediaPlayer (); mbtnstop = ( button) Findviewbyid (r.id.btn_stop), Mbtnpause = (button) Findviewbyid (r.id.btn_pause); mbtnplay = (Button) Findviewbyid (r.id.btn_play); mbtnnext = (Button) Findviewbyid (r.id.btn_next); mbtnpre = (Button) Findviewbyid (R.id.btn _PRE); Mmusiclistview = (ListView) Findviewbyid (R.id.music_listview); Getmusiclist (); Gets the Music playlist Mbtnstop.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) {if ( Mmediaplayer.isplaying ()) {Mmediaplayer.reset ();}}}); Mbtnpause.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {if ( Mmediaplayer.isplaying ()) {mmediaplayer.pause (); Mbtnpause.settext ("Continue");} else {mmediaplayer.start (); Mbtnpause.settext ("Pause");}}); Mbtnplay.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {playmusic (Music_path + Mmusiclist.get (Mcurrentmusicitem));}); Mbtnnext.setonclicklisteneR (New View.onclicklistener () {@Overridepublic void OnClick (View v) {nextmusic ();}}); Mbtnpre.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {premusic ();}});} private void Playmusic (String path) {try {mmediaplayer.reset (); Mmediaplayer.setdatasource (path); Mmediaplayer.prepare (); Mmediaplayer.start (); Mmediaplayer.setoncompletionlistener (new Mediaplayer.oncompletionlistener () {@Overridepublic void oncompletion (MediaPlayer MP) {Nextmusic ();}});} catch (Exception e) {e.printstacktrace ();}} private void Getmusiclist () {File home = new File (Music_path); if (Home.listfiles (new Musicfilter ()). length > 0) {for (F Ile File:home.listFiles (New Musicfilter ())) {Mmusiclist.add (File.getname ());} arrayadapter<string> adapter = new Arrayadapter<string> (Mcontext, R.layout.music_item,r.id.music_item_ TV, mmusiclist); Mmusiclistview.setadapter (adapter); Mmusiclistview.setonitemclicklistener (new Adapterview.onitemclicklistener () {@Overridepublic void Onitemclick (AdApterview<?> L, View view,int position, long id) {Mcurrentmusicitem = Position;playmusic (Music_path + mmusiclist.ge T (Mcurrentmusicitem));}});}} private void Nextmusic () {if (++mcurrentmusicitem >= mmusiclist.size ()) {Mcurrentmusicitem = 0;} Playmusic (Music_path + mmusiclist.get (Mcurrentmusicitem));} private void Premusic () {if (--mcurrentmusicitem < 0) {Mcurrentmusicitem = Mmusiclist.size ()-1;} Playmusic (Music_path + mmusiclist.get (Mcurrentmusicitem));} Class Musicfilter implements FilenameFilter {@Overridepublic Boolean accept (File dir, String filename) {return FILENAME.E Ndswith ("MP3");}} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;}                @Overrideprotected void OnDestroy () {Super.ondestroy (); Mmediaplayer.stop ();       Mmediaplayer.reset ();        mmediaplayer.release ();  } @Overrideprotectedvoid Onresume () {super.onresume (); if (mmediaplayer.isplaying ()) {Mbtnpause.settext ("pause");} Else{mbtnpause.settext ("Continue");}}}

3. The ListView is also used here, and there is also a resource file: Layout/music_item.xml:

<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" 50DP ">    <textview        Android:id= "@+id/music_item_tv"        android:layout_width= "wrap_content"        android:layout_height= "Wrap_ Content "        android:layout_centervertical=" true "/></relativelayout>



Explanation article:

The code is a bit more, so let's focus on it. First of all, to introduce the MediaPlayer class, is specifically used in Android to deal with music requests, in a separate thread, the life cycle does not die with the anctivity.

Life cycle:

Explain: To use MediaPlayer need to first new object out, and then call its reset () method into the idle state, through Setdatasource () can set the playback directory, enter the initalized state, and then call The prepare () method enters the prepare state, at which point the start () method can be called to start playing the music. Pause and stop each call to the pause () and stop () methods. It is best to go back to the idle state at the exit, call Reset (), and then call Release () to exit.

Let's see how the code is written:

Play Music:

private void Playmusic (String path) {try {mmediaplayer.reset (); Mmediaplayer.setdatasource (path); Mmediaplayer.prepare (); Mmediaplayer.start (); Mmediaplayer.setoncompletionlistener (new Mediaplayer.oncompletionlistener () {@Overridepublic void oncompletion (MediaPlayer MP) {Nextmusic ();}});} catch (Exception e) {e.printstacktrace ();}}
We can see that it's all about life cycle, reset (), Setdatasource (), start (), prepare (), where path is the specific path to the music file (as an entry), where the Listener event is set: OnCo Mpletionlistener, is when a piece of music is automatically triggered when finished, here we play the next music directly. If you want to do a functional single loop, then directly re-broadcast the current music can be, is not very simple.


Stop: If you play again, reset directly to the initial state

if (mmediaplayer.isplaying ()) {       mmediaplayer.reset ();}


Pause: Determines if playback is paused, if it pauses on playback, and the pause button is set to continue, if it is the Continue button, the music is played after the click, and the Set button is paused. We use words to replace them here.

if (mmediaplayer.isplaying ()) {mmediaplayer.pause (); Mbtnpause.settext ("Continue");} else {mmediaplayer.start (); Mbtnpause.settext ("Pause");}

Next: Here we need a class variable Mcurrentmusicitem flag where the song is currently playing, that is, the first song. If you loop to 0 at the end, continue playing.

private void Nextmusic () {if (++mcurrentmusicitem >= mmusiclist.size ()) {Mcurrentmusicitem = 0;} Playmusic (Music_path + mmusiclist.get (Mcurrentmusicitem));}

Previous: Same as the next thought, do not explain

private void Premusic () {if (--mcurrentmusicitem < 0) {Mcurrentmusicitem = Mmusiclist.size ()-1;} Playmusic (Music_path + mmusiclist.get (Mcurrentmusicitem));}


We need to see what the incoming to Playmusic (String path) parameter is.

This sets the music playback path to "mnt/sdcard/":

private static final String music_path = new String ("/sdcard/");

Then in the directory, all the files with the suffix "MP3" are added to the mmusiclist<string>, stitching can get the path of the music, for example: Mnt/sdcard/dreamer.mp3, note "/sdcard/" the first "/" table The root directory, in fact, is "mnt/", this is from Linux, we do not misunderstand.

Private list<string> mmusiclist = new arraylist<string> ();
private void Getmusiclist () {File home = new File (Music_path); if (Home.listfiles (new Musicfilter ()). length > 0) {for (F Ile File:home.listFiles (New Musicfilter ())) {Mmusiclist.add (File.getname ());} arrayadapter<string> adapter = new Arrayadapter<string> (Mcontext, R.layout.music_item,r.id.music_item_ TV, mmusiclist); Mmusiclistview.setadapter (adapter); Mmusiclistview.setonitemclicklistener (new Adapterview.onitemclicklistener () {@Overridepublic void Onitemclick (adapterview<?> l, View view,int position, Long id) {Mcurrentmusicitem = Position;playmusic (Music_path + mmusiclist.get (Mcurrentmusicitem));}});}}


Finally, we need to invoke the life cycle of MediaPlayer in the activity life cycle, otherwise, when your activity is destroyed, MediaPlayer is still there, it is not very old fire:

@Overrideprotected void OnDestroy () {Super.ondestroy (); Mmediaplayer.stop ();                Mmediaplayer.reset ();          mmediaplayer.release ();       }


Here has been the music player the core of the code thanks, if you want to do the extension is very good extension, modify the interface, modify the music list, etc., I hope to help you.



Android Getting Started notes-multimedia-MediaPlayer

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.