使用MediaPlayer播放、暂停、停止音乐

时间:2024-03-05 07:12:26
package com.pingyijinren.test;

import android.media.MediaPlayer;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;


public class MainActivity extends AppCompatActivity{
    private Button play;
    private Button pause;
    private Button reset;
    private MediaPlayer mediaPlayer;
    private File file;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        play=(Button)findViewById(R.id.play);
        pause=(Button)findViewById(R.id.pause);
        reset=(Button)findViewById(R.id.reset);
        mediaPlayer=new MediaPlayer();

        try{
            file=new File(Environment.getExternalStorageDirectory()+"/netease/cloudmusic/Music/Apnea - Tongue.mp3");
            mediaPlayer.setDataSource(file.getPath());
            mediaPlayer.prepare();
        }
        catch(IOException e){
            Toast.makeText(this,"音乐不存在!",Toast.LENGTH_SHORT).show();
        }

        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!mediaPlayer.isPlaying()){
                    mediaPlayer.start();
                }
            }
        });

        pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mediaPlayer.isPlaying()){
                    mediaPlayer.pause();
                }
            }
        });

        reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mediaPlayer.isPlaying()){
                    mediaPlayer.reset();

                    try{
                        mediaPlayer.setDataSource(file.getPath());
                        mediaPlayer.prepare();
                    }
                    catch(IOException e){}
                }
            }
        });
    }

    @Override
    public void onDestroy(){
        super.onDestroy();

        if(mediaPlayer!=null){
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }
}