Given the ability to play an audio file, the simplest way to provide the ability to play audio files in your application is to take advantage of the features of the built-in "music" app-even if you use the system's own or installed music player to play the specified audio file.
This example is relatively simple, the following direct source code:
Layout file Activity_main:
<relativelayout 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:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: Context= ". Mainactivity "> <textview android:id=" @+id/textview "android:layout_width=" Wrap_content "and roid:layout_height= "Wrap_content" android:layout_centerhorizontal= "true" android:text= "music player instance"/> < ; Button android:id= "@+id/button" android:layout_width= "match_parent" android:layout_height= "Wrap_conte NT "android:layout_below=" @id/textview "android:text=" Play Music "/></relativelayout>
code file Mainactivity:
Package Com.mutimediademo3audio;import Java.io.file;import Android.app.activity;import android.content.Intent; Import Android.net.uri;import android.os.bundle;import Android.os.environment;import Android.view.View;import Android.view.view.onclicklistener;import Android.widget.button;public class Mainactivity extends Activity implements Onclicklistener {private button button; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); button = (button) Findviewbyid (R.id.button); Button.setonclicklistener (this);} @Overridepublic void OnClick (View v) {switch (V.getid ()) {case r.id.button:/** * will be generic android.content.Intent.ACTION_ The view intent data is set to the URI of an audio file, * and its MIME type is established so that Android can pick the appropriate application for playback. */intent Intent = new Intent (Android.content.Intent.ACTION_VIEW); File sdcard = Environment.getexternalstoragedirectory (); File AudioFile = new file (Sdcard.getpath () + "/good.mp3"), and/or place a file name in the SD card that is called the good mp3. Intent.setdataandtype (Uri. FromFile (AudioFile), "Audio/mp3"); StartActivity (intent); break;default:break;}}
Source:
Click to download source code
Android uses built-in audio player with intent