package com.baidu.ai.sample.util;


import android.media.AudioAttributes;
import android.media.MediaPlayer;
import android.util.Log;

public class ZMediaPlayer extends MediaPlayer
        implements MediaPlayer.OnErrorListener,
        MediaPlayer.OnCompletionListener,
        MediaPlayer.OnPreparedListener {
    private static final String TAG = "ZMediaPlayer";

    public ZMediaPlayer() {
        super();
        this.setOnErrorListener(this);
        this.setOnCompletionListener(this);

        /** 强制设置音频 Attributes */
        this.setAudioAttributes(
                new AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                        .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
                        .build());
    }

    public void play(String url) {
        if (this.isPlaying()) {
            this.pause();
            this.stop();
            Log.i(TAG, "stop old play item!");
        }

        try {
            this.reset();
            this.setDataSource(url);
            this.prepare();
            this.start();
            Log.i(TAG, "start play item, " + url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stop2() {
        if (this.isPlaying()) {
            this.pause();
            this.stop();
        }
    }

    public void destroy() {
        try {
            if (this.isPlaying()) {
                this.stop();
            }
            this.release();
            Log.i(TAG, "destroy mediaPlayer");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
        Log.i(TAG, "onError, what:" + what + ", extra:" + extra);
        return false;
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        Log.i(TAG, "onCompletion ");
    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        Log.i(TAG, "onPrepared ");
    }
}
