|
|
@@ -0,0 +1,103 @@
|
|
|
+package com.yingyangfly.baselib.player;
|
|
|
+
|
|
|
+import android.content.Context;
|
|
|
+import android.media.AudioManager;
|
|
|
+import android.media.MediaPlayer;
|
|
|
+import android.text.TextUtils;
|
|
|
+
|
|
|
+import java.io.IOException;
|
|
|
+
|
|
|
+/**
|
|
|
+ * @author 王鹏鹏
|
|
|
+ */
|
|
|
+public class VoicePlayer {
|
|
|
+
|
|
|
+ private static volatile VoicePlayer instance = null;
|
|
|
+ private AudioManager audioManager;
|
|
|
+ private MediaPlayer mediaPlayer;
|
|
|
+ private boolean isPause;
|
|
|
+ private boolean isLoading;
|
|
|
+ private MediaPlayer.OnCompletionListener onCompletionListener;
|
|
|
+
|
|
|
+ public static VoicePlayer getInstance(Context context) {
|
|
|
+ if (instance == null) {
|
|
|
+ synchronized (VoicePlayer.class) {
|
|
|
+ if (instance == null) {
|
|
|
+ instance = new VoicePlayer(context);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return instance;
|
|
|
+ }
|
|
|
+
|
|
|
+ private VoicePlayer(Context cxt) {
|
|
|
+ Context baseContext = cxt.getApplicationContext();
|
|
|
+ audioManager = (AudioManager) baseContext.getSystemService(Context.AUDIO_SERVICE);
|
|
|
+ mediaPlayer = new MediaPlayer();
|
|
|
+ }
|
|
|
+
|
|
|
+ public MediaPlayer getPlayer() {
|
|
|
+ return mediaPlayer;
|
|
|
+ }
|
|
|
+
|
|
|
+ public boolean isPlaying() {
|
|
|
+ return mediaPlayer.isPlaying();
|
|
|
+ }
|
|
|
+
|
|
|
+ public void play(final String url, final MediaPlayer.OnCompletionListener listener) {
|
|
|
+ if (mediaPlayer.isPlaying()) {
|
|
|
+ stop();
|
|
|
+ }
|
|
|
+ isPause = false;
|
|
|
+ onCompletionListener = listener;
|
|
|
+ try {
|
|
|
+ setSpeaker();
|
|
|
+ if (!TextUtils.isEmpty(url)) {
|
|
|
+ mediaPlayer.setDataSource(url);
|
|
|
+ mediaPlayer.prepareAsync();
|
|
|
+ isLoading = true;
|
|
|
+ mediaPlayer.setOnPreparedListener(mp -> {
|
|
|
+ isLoading = false;
|
|
|
+ mediaPlayer.start();
|
|
|
+ });
|
|
|
+ mediaPlayer.setOnCompletionListener(mp -> {
|
|
|
+ stop();
|
|
|
+ onCompletionListener = null;
|
|
|
+ });
|
|
|
+ }
|
|
|
+ } catch (IOException e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public void stop() {
|
|
|
+ isPause = false;
|
|
|
+ isLoading = false;
|
|
|
+ mediaPlayer.stop();
|
|
|
+ mediaPlayer.reset();
|
|
|
+ if (onCompletionListener != null) {
|
|
|
+ onCompletionListener.onCompletion(mediaPlayer);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public void pause() {
|
|
|
+ isPause = true;
|
|
|
+ mediaPlayer.pause();
|
|
|
+ }
|
|
|
+
|
|
|
+ public void start() {
|
|
|
+ isPause = false;
|
|
|
+ mediaPlayer.start();
|
|
|
+ }
|
|
|
+
|
|
|
+ public boolean isPause() {
|
|
|
+ return isPause;
|
|
|
+ }
|
|
|
+
|
|
|
+ private void setSpeaker() {
|
|
|
+ audioManager.setMode(AudioManager.MODE_NORMAL);
|
|
|
+ audioManager.setSpeakerphoneOn(true);
|
|
|
+ mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
|
|
|
+ }
|
|
|
+
|
|
|
+}
|