我最近发布了一个应用程序,用户报告崩溃,因为我的程序包含方法setNextMediaPlayer().我现在意识到这只适用于API 16,我的应用程序支持API 8.我想知道是否有另一种方法可以达到同样的效果.
我的应用程序有一些文本到语音,我正在做的是创建一个MediaPlayers的ArrayList,每个都有一个简短的声音文件,然后一个接一个地播放它们.如果我从代码中删除此方法,则音频变得太不连贯而无法理解.
我在考虑使用SoundPool类,但是没有OnCompleteListener,所以我不确定如何做到这一点.
所以基本上我的问题是:有没有办法在不使用setNextMediaPlayer()方法的情况下在音频文件之间无缝转换?
非常感谢你花时间陪伴!
编辑
private class CompatMediaPlayer extends MediaPlayer implements OnCompletionListener { private boolean mCompatMode = true; private MediaPlayer mNextPlayer; private OnCompletionListener mCompletion; public CompatMediaPlayer() { try { MediaPlayer.class.getMethod("setNextMediaPlayer",MediaPlayer.class); mCompatMode = false; } catch (NoSuchMethodException e) { mCompatMode = true; super.setOnCompletionListener(this); } } public void setNextMediaPlayer(MediaPlayer next) { if (mCompatMode) { mNextPlayer = next; } else { super.setNextMediaPlayer(next); } } @Override public void setOnCompletionListener(OnCompletionListener listener) { if (mCompatMode) { mCompletion = listener; } else { super.setOnCompletionListener(listener); } } @Override public void onCompletion(MediaPlayer mp) { if (mNextPlayer != null) { // as it turns out,starting a new MediaPlayer on the completion // of a prevIoUs player ends up slightly overlapping the two // playbacks,so slightly delaying the start of the next player // gives a better user experience SystemClock.sleep(50); mNextPlayer.start(); } mCompletion.onCompletion(this); } }
// assigns a file to each media player mediaplayers = new ArrayList<CompatMediaPlayer>(); for (int i = 0; i < files.size(); i++) { mediaplayers.add((CompatMediaPlayer) CompatMediaPlayer.create(this,files.get(i))); }
但我得到一个类强制转换异常因为MediaPlayer无法转换为CompatMediaPlayer.
解决方法
创建将与onCompletionListener一起使用的Compat播放器,以启动下一个播放器:
public void onCompletion(MediaPlayer mp) { if (mCompatMode && mNextPlayer != null) { mNextPlayer.prepare(); mNextPlayer.start(); } }
在构造函数中的某处检查是否存在名为“setNextMediaPlayer”的方法(或检查SDK版本)
mCompatMode = Build.VERSION.SDK_INT< 16; 定义像这样的方法:
public void setNextMediaPlayer(MediaPlayer next) { if (mCompatMode) { mNextPlayer = next; } else { super.setNextMediaPlayer(next); } }