app播放app工程自带(不是SD卡里的)的音乐文件。
1.在工程res文件夹里新建raw文件夹,在raw文件夹里放置一份mp3文件。
2.在MainActivity.java文件里
public class MainActivity extends Activity下面一行添加:
private MediaPlayer mp=new MediaPlayer();3.在MainActivity.java文件里onCreate()里面添加:
MediaPlayer mp =MediaPlayer.create(this, R.raw.music); mp.start();具体范例:
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:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:orientation="horizontal"> <Button android:id="@+id/play" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="4" android:text="播放"/> </LinearLayout>MainActivity.java文件内容·如下:
package com.example.testmusic; import android.app.Activity; import android.media.MediaPlayer; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { private MediaPlayer mp=new MediaPlayer(); private Button play; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); play=(Button) findViewById(R.id.play); final MediaPlayer mp =MediaPlayer.create(this, R.raw.music); play.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mp.start(); } }); } @Override protected void onDestroy() { super.onDestroy(); if (mp != null) { mp.stop(); mp.release(); } } }具体效果: