【发布时间】:2018-06-09 22:18:48
【问题描述】:
我正在使用 Xamarin.Forms,在我的 android 项目中,我有一个自定义 AudioManager 类来播放音频文件。
我的代码使用 Android.Media.MediaPlayer 类从 assets 目录播放嵌入的音频文件。
此代码在 API24 及更高版本的设备上运行良好。 但对于 API 23 及更低版本的设备,它会在 mediaplayer.SetDataSource(assetFileDescriptor) 上生成异常。
异常读取“Java.Lang.NoSuchMethodError: no non-static method "Landroid/media/MediaPlayer;.setDataSource(Landroid/content/res/AssetFileDescriptor;)”
这是一个已知问题吗?如果是这样,你如何解决这个问题。
我的代码:
public void PlayEmbeddedSound(string soundFileName)
{
if (_mediaPlayer != null && _mediaPlayer.IsPlaying)
{
_mediaPlayer?.Stop();
}
_mediaPlayer?.Reset();
_mediaPlayer?.Release();
_mediaPlayer = new MediaPlayer();
if (Android.OS.Build.VERSION.SdkInt > Android.OS.BuildVersionCodes.Lollipop)
{
//not supported @ API16
var attributes = new AudioAttributes.Builder()
.SetUsage(AudioUsageKind.VoiceCommunication)
.SetContentType(AudioContentType.Speech)
.SetFlags(AudioFlags.AudibilityEnforced)
.Build();
_mediaPlayer.SetAudioAttributes(attributes);
}
_mediaPlayer.SetVolume(1F, 1F);
var assetsSoundsDir = "Sounds";
var soundPath = System.IO.Path.Combine(assetsSoundsDir,soundFileName);
var assetFileDescriptor =
Android.App.Application.Context.Assets.OpenFd(soundPath);
_mediaPlayer.Prepare();
_mediaPlayer.Completion -= _mediaPlayer_Completion;
_mediaPlayer.Completion += _mediaPlayer_Completion;
_mediaPlayer.Start();
}
【问题讨论】:
标签: android xamarin.forms android-mediaplayer media-player