播放音频,主要用到一个类MediaPlayer。我们需要实现的这个网络音频播放工具类就是对这个类的一系列方法进行封装的
因为代码比较简单,就直接贴出代码并略微解释一下。
public class VoicePlayer implements MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener {
public MediaPlayer mediaPlayer;
private boolean isCompletion = false;
private boolean isPrepared = false;
public VoicePlayer() {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
} catch (Exception e) {
Log.e("mediaPlayer", "error", e);
}
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
/**
* 播放
*/
public void play() {
if (mediaPlayer != null) {
mediaPlayer.start();
}
}
public void playUrl(String videoUrl) {
try {
isCompletion = false;
mediaPlayer.reset();
mediaPlayer.setDataSource(videoUrl);
mediaPlayer.prepare();
} catch (IllegalArgumentException | IllegalStateException | IOException e) {
e.printStackTrace();
}
}
/**
* 暂停
*/
public void pause() {
mediaPlayer.pause();
}
public void stop() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
/**
* 重播
*/
public void replay() {
if (mediaPlayer != null) {
mediaPlayer.seekTo(0);
}
}
@Override
public void onPrepared(MediaPlayer arg0) {
isPrepared = true;
}
@Override
public void onCompletion(MediaPlayer arg0) {
isCompletion = true;
}
/**
* 是否准备完毕
*/
public boolean isPrepared() {
return isPrepared;
}
/**
* 是否播放完毕
*/
public boolean isCompletion() {
return isCompletion;
}
}
- 音频准备:
mediaPlayer.setOnPreparedListener(this);
当音频加载完成之后会回调。所以在这之前可以让icon变成一个圆形进度条让它转动,加载完成之后再将回调抛给调用类,这里就不写示例了 - 音频重播:
mediaPlayer.seekTo(0);
很简单,就是让音频的位置置于0 - 注意资源释放