Android媒体播放器音频故障/断断续续仅在较新的设备上

reg*_*mar 6 audio android android-mediaplayer nexus-10 nexus-5

我有一个相当标准的媒体播放器对象,它在onCreate中启动,并在我的应用程序中循环播放背景音乐.该文件不是很大,它是一个6MB的MP3.来自onCreate:

MediaPlayer mp;
mp = MediaPlayer.create(MainActivity.this, R.raw.lostmexicancity);
mp.setLooping(true);
mp.setVolume(0.4f, 0.4f);
mp.start();
Run Code Online (Sandbox Code Playgroud)

这适用于我的大多数测试设备,包括旧手机,三星Galaxy Tab 2 10"平板电脑,甚至是Nexus 4.

不幸的是,我遇到了新设备的问题,我在Nexus 5和较新的Nexus 10上遇到音频故障/口吃.这些问题只发生在较新的设备上,通常在正确播放几秒钟后,而不是立即发生.我的Nexus 4和5都运行Android 4.4.4但问题只发生在Nexus 5上.

当我暂停媒体播放器对象并在短时间内播放不同的媒体播放器对象(在游戏中为短战而战斗音乐)时,这个问题似乎会加剧,但即使没有这种额外的复杂情况,也会出现故障.

我已经读过Android的新版本引起了Mediaplayer的问题,但我还没有得到修复或建议.

有没有其他人遇到过这个可以提出修复或解决方法的问题?感谢您的时间!

Gan*_*458 0

我注意到我的 Android 设备上也发生了这种情况。

我注意到您没有调用Prepare(),这是播放音频之前的一个重要函数。编辑 - 仅当使用 new 创建 MediaPlayer 时才需要调用prepare,而不是使用内置 MediaPlayer.Create()。

至于您在源之间切换时的问题,我建议您在要播放的音频中的确切时间调用 SeekTo() ,并使用 SeekComplete 侦听器等待该位置。在评论中,我有一小行黑客代码,直到调用开始之后才设置 mediaPlayer 上的音量。这似乎减少了口吃,但您可能会丢失音频的前一小部分。

我使用的是 Xamarin Studio C#,但即使您使用的是 Java,同样的方法也应该有效。

MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.SetAudioStreamType (Android.Media.Stream.Music);
mediaPlayer.SetDataSource ("dataSourcePath");

mediaPlayer.Looping = true;

//It is necessary to call prepare after setting the data source
mediaPlayer.Prepare ();

//Ensure the audio has seeked to the position you need
bool seekingComplete = false;
mediaPlayer.SeekComplete += (object sender, EventArgs e) => {
    seekingComplete = true;
};

mediaPlayer.SeekTo(0);

//Forces the audio to complete seeking
while(seekingComplete == false)
{
    //Here, you just wait 2 milliseconds at a time 
    //for this buffering and seeking to complete
    await Task.Delay(2);
}

mediaPlayer.Start();

//Hacky way to prevent the glitch sound at the start is to set the
//volume after calling start
//mediaPlayer.SetVolume(0.4f, 0.4f);
Run Code Online (Sandbox Code Playgroud)