自定义录音播放工具类MediaManager可播放网络音频

时间:2021-10-27 16:09:13

代码:

/**
* Created by qianye on 2017/1/29.
*/


public class MediaManager {
private static MediaPlayer mMediaPlayer;
private static boolean isPause;

public static void playSound(String soundPath, MediaPlayer.OnCompletionListener onCompletionListener) {

if (mMediaPlayer == null) {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
mMediaPlayer.reset();
return false;
}
});
} else {
mMediaPlayer.reset();
}

mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnCompletionListener(onCompletionListener);
try {
mMediaPlayer.setDataSource(soundPath);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void pause() {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
isPause = true;
}
}

public static void resume() {
if (mMediaPlayer != null && isPause) {
mMediaPlayer.start();
isPause = false;
}
}

public static void release() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}

public static boolean isPlaying() {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
return true;
}
return false;
}

}

使用:

//参数1:声音路径,可以是网络地址 参数2:播放完成监听
MediaManager.playSound(soundPath, new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {

}
});