</pre><pre name="code" class="html">
定义动画xml
<pre name="code" class="html"><animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false" >
<item
android:drawable="@drawable/bai_one"
android:duration="500"/>
<item
android:drawable="@drawable/bai_two"
android:duration="500"/>
<item
android:drawable="@drawable/bai_three"
android:duration="500"/>
</animation-list>
</pre><pre code_snippet_id="536555" snippet_file_name="blog_20141129_17_8981203" name="code" class="java">
自定义语音播放类
public class RemarkPlayer implements OnCompletionListener {
/** 播放动画的图片 */
private ImageView playerView;
/** 语音播放对象 */
private MediaPlayer remarkPlayer;
/** 语音播放的位置 */
private int playerIndex = 0;
private AnimationDrawable animationDrawable;
public MediaPlayer getRemarkPlayer() {
if (remarkPlayer == null)
remarkPlayer = new MediaPlayer();
return remarkPlayer;
}
/**
* 为mediaplayer设置路径准备播放
*/
public void initRemarkPlayer(Context context, String url)
throws IllegalArgumentException, IllegalStateException, IOException {
if (remarkPlayer != null) {
// remarkPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
Uri uri = Uri.parse(url);
remarkPlayer.reset();
remarkPlayer.setDataSource(context, uri);
remarkPlayer.prepare();
}
}
/**
* 将要播放动画的图片传进来
*/
public void setAnimView(ImageView playerView) {
// TODO Auto-generated method stub
if (playerView != null) {
this.playerView = playerView;
}
if (remarkPlayer != null) {
remarkPlayer.setOnCompletionListener(this);
}
}
/**
* 开始播放音频
*/
public void start() {
if (remarkPlayer != null) {
if (!remarkPlayer.isPlaying()) {
if (playerIndex > 0) {
// 当语音播放暂停过以后,继续播放时,动画的播放时间会比语音结束的时间长,seeTO之后,可以保持一致
remarkPlayer.seekTo(playerIndex);
}
remarkPlayer.start();
if (playerView != null) {
// 为动画图片设置写好的动画xml,得到AnimationDrawable对象后,调用AnimationDrawable对象的start方法开始播放动画
playerView.setImageResource(R.anim.voice_player_anim);
animationDrawable = (AnimationDrawable) playerView
.getDrawable();
animationDrawable.start();
}
} else {
// 语音暂停时,先关掉动画,继续播放时再开始
remarkPlayer.pause();
playerIndex = remarkPlayer.getCurrentPosition();
if (playerView != null) {
animationDrawable.stop();
// playerView.setImageResource(R.drawable.lu_three);
}
}
}
}
public void pause() {
if (remarkPlayer != null) {
if (remarkPlayer.isPlaying()) {
remarkPlayer.stop();
playerIndex = 0;
if (playerView != null) {
animationDrawable.stop();
// playerView.setImageResource(R.drawable.lu_three);
}
}
}
}
public void destroy() {
if (remarkPlayer != null) {
if (remarkPlayer.isPlaying()) {
remarkPlayer.stop();
if (playerView != null) {
animationDrawable.stop();
playerIndex = 0;
playerView.setImageResource(R.drawable.lu_three);
}
}
remarkPlayer.release();
}
}
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
// 监听语音播放完毕,关闭语音,结束动画。
// 当语音暂停后,继续播放时,结束时间会重新开始记时,所以实际结束时间会比语音播放时间长,导致当语音结束时,动画还在播放
if (playerView != null) {
animationDrawable.stop();
playerIndex = 0;
playerView.setImageResource(R.drawable.lu_three);
}
}
}