首先的在Manifest文件里配置;
XML:
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Music:"
android:paddingLeft="5dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_h
eight="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/playbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="41dp"
android:layout_marginLeft="41dp"
android:text="Play"
android:textAllCaps="false" />
<Button
android:id="@+id/pausebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Pause"
android:textAllCaps="false" />
<Button
android:id="@+id/stopbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="41dp"
android:layout_marginRight="41dp"
android:text="Stop"
android:textAllCaps="false" />
</LinearLayout>
</LinearLayout>
Java:
import android.media.MediaPlayer;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.VideoView;
import java.io.File;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button playbtn;
private Button pausebtn;
private Button stopbtn;
private MediaPlayer mediaPlayer = new MediaPlayer();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
initVideoPath();
}
private void init()
{
playbtn = findViewById(R.id.playbtn);
pausebtn = findViewById(R.id.pausebtn);
stopbtn = findViewById(R.id.stopbtn);
playbtn.setOnClickListener(this);
pausebtn.setOnClickListener(this);
stopbtn.setOnClickListener(this);
}
private void initMediaPlayer()
{
try{
File file = new File(Environment.getExternalStorageDirectory(),"Honor.mp3");
mediaPlayer.setDataSource(file.getPath());
mediaPlayer.prepare();
}catch (Exception e)
{
e.printStackTrace();
}
}
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.playbtn:
if(!mediaPlayer.isPlaying())
mediaPlayer.start();
break;
case R.id.pausebtn:
if(mediaPlayer.isPlaying())
mediaPlayer.pause();
break;
case R.id.stopbtn:
if(mediaPlayer.isPlaying())
mediaPlayer.reset();
break;
}
@Override
protected void onDestroy()
{
super.onDestroy();
if(mediaPlayer !=null)
{
mediaPlayer.stop();
mediaPlayer.release();
}
}
}