播放资源音乐文件
在/res/raw/目录下放a.mp3文件
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.a)
package com.example.androidtest;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.util.Log;
public class MainActivity extends Activity implements OnCompletionListener, OnTouchListener, OnClickListener {
MediaPlayer mediaPlayer;
View theView;
Button stopButton, startButton;
int position = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stopButton = (Button)findViewById(R.id.StopButton);
startButton = (Button)findViewById(R.id.StartButton);
stopButton.setOnClickListener(this);
startButton.setOnClickListener(this);
theView = this.findViewById(R.id.theview);
theView.setOnClickListener(this);
mediaPlayer = MediaPlayer.create(this, R.raw.a);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
}
public boolean onTouch(View v, MotionEvent me)
{
if (me.getAction() == MotionEvent.ACTION_MOVE) {
if (mediaPlayer.isPlaying()) {
position = (int)(me.getX() * mediaPlayer.getDuration() / theView.getWidth());
Log.d("SEEK", "" + position);
mediaPlayer.seekTo(position);
}
}
return true;
}
public void onCompletion(MediaPlayer mp)
{
mediaPlayer.start();
mediaPlayer.seekTo(position);
}
public void onClick(View v)
{
if (v == stopButton) {
mediaPlayer.pause();
} else if (v == startButton) {
mediaPlayer.start();
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:text="Start" android:id="@+id/StartButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="Stop" android:id="@+id/StopButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<View android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/theview" />
</LinearLayout>