播放的文件放到assets文件夹中,文件名 1.mp3
MainActivity
package com.media.player;
import java.io.IOException;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private String path = "file:///android_asset/1.mp3";
private MediaPlayer mediaPlayer;
private TextView text;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView) findViewById(R.id.text);
button = (Button) findViewById(R.id.button);
button.setText("Play");
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mediaPlayer.isPlaying()) {
text.setText("Play pause");
mediaPlayer.pause();
button.setText("Play");
} else {
text.setText("Playing");
mediaPlayer.start();
button.setText("Pause");
}
}
});
mediaPlayer = new MediaPlayer();
InitMusic(path);
mediaPlayer
.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
// ResetMusic(mp3Path);
text.setText("Play start");
mediaPlayer.start();
}
});
}
public void InitMusic(String path) {
mediaPlayer.reset();
try {
AssetFileDescriptor descriptor = getAssets().openFd("1.mp3");
mediaPlayer.setDataSource(descriptor.getFileDescriptor());
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
if (mediaPlayer != null)
mediaPlayer.release();
super.onDestroy();
}
}
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:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</LinearLayout>