[android] 01_音乐播放器-MediaPlayer

Android 4.0

音乐播放器 

1、设置屏幕常亮   MediaPlayer.setScreenOnWhilePlaying()  or  MediaPlayer.setWakeMode()
需要权限:<uses-permission android:name = "android.permission.WAKE_LOCK" />

2、设置声音格式
mediaPlayer . setAudioStreamType ( AudioManager . STREAM_MUSIC );
AudioManager . STREAM_MUSIC 音频资源
AudioManager . STREAM_ALARM 报警闹铃
AudioManager . STREAM_RING 铃声(40秒以下)

3、要写在service中播放音乐,这里演示就写在activity中了

4、设置同步准备
mediaPlayer.prepareAsync();// 异步的同步,一般的音频用同步,而视频用异步,这样就不能将start()写外面了,而要写在setOnPreparedListener监听事件里面
                // 监听准备完毕事件,一般异步
                mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        mediaPlayer.start();
                    }
                });
MediaPlayer生命周期:
核心代码:
package cn.zengfansheng.musicplay;
 
import java.io.File;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
    private EditText et_path;
    private Button bt_pause;
    private MediaPlayer mediaPlayer;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        et_path = (EditText) this.findViewById(R.id.et_path);
        bt_pause = (Button) this.findViewById(R.id.bt_pause);
    }
    /**
     * TODO 1、开始播放
     *
     * @param view
     */

    public void start(View view) {
        try {
            // 1、获取音乐路径
            String audioPath = et_path.getText().toString().trim();
            File file = new File(audioPath);
            if (file.exists() && file.length() > 0) {
                // 2
                // MediaPlayer mediaPlayer = new MediaPlayer();//这里使用的是局部变量了。
                mediaPlayer = new MediaPlayer();
                // 3、设置音频类型
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                // STREAM_ALARM 报警音 STREAM_RING 响铃
                mediaPlayer.setDataSource(getApplicationContext(), Uri.parse(audioPath));
 
                // mediaPlayer.prepare();// 同步的准备
                // mediaPlayer.start();//
 
                mediaPlayer.setLooping(true);// whether to loop or not是否循环播放
 
                mediaPlayer.prepareAsync();// 异步的同步,一般的音频用同步,而视频用异步,这样就不能将start()写外面了,而要写在setOnPreparedListener监听事件里面
                // 监听准备完毕事件,一般异步
                mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        mediaPlayer.start();
                    }
                });
 
                // 监听播放完毕事件
                mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        System.out.println("播放完毕。。。");
                    }
                });
                // 监听出现出错信息
                mediaPlayer.setOnErrorListener(new OnErrorListener() {
                    @Override
                    public boolean onError(MediaPlayer mp, int what, int extra) {
                        // mp ,what 错误的原因 ,extra 额外的的信息
                        System.out.println("音频不完整,发生错误了");
                        return false;
                    }
                });
                Toast.makeText(getApplicationContext(), "开始播放。。。"+audioPath.substring(audioPath.lastIndexOf("/")+1), 0).show();
            } else {
                Toast.makeText(getApplicationContext(), "路径不能为空!", 0).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "不支持的音频格式。。。", 0).show();
        }
    }
    /**
     * TODO 2、暂停和既相互播放
     *
     * @param view
     */

    public void pause(View view) {
 
        if ("续播".equals(bt_pause.getText().toString().trim())) {
            bt_pause.setText("暂停");
            mediaPlayer.start();// Starts or resumes playback
            Toast.makeText(getApplicationContext(), "继续播放", 0).show();
            return;
        }
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            bt_pause.setText("续播");
            Toast.makeText(getApplicationContext(), "暂停播放", 0).show();
        }
    }
    /**
     * TODO 3、停止播放
     *
     * @param view
     */

    public void stop(View view) {
 
        if (mediaPlayer != null && mediaPlayer.isPlaying()) { 
          mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;  
            Toast.makeText(getApplicationContext(), "停止播放", 0).show();
        }
    }
    /**
     * TODO 4、重新播放
     *
     * @param view
     */

    public void replay(View view) {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.seekTo(0);
            Toast.makeText(getApplicationContext(), "重新播放", 0).show();
        }
    }
}
结果:
问题1:多按几次播放,会播放多次
问题2:按了停止播放,再按暂停会报异常
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;