android 媒体播放器 SetDataSource(AssetFileDescriptor) 不工作 < API 24

android mediaplayer SetDataSource(AssetFileDescriptor) does not work < API 24

我正在使用 Xamarin.Forms,在我的 android 项目中,我有一个自定义 AudioManager class 来播放音频文件。

我有代码可以使用 Android.Media.MediaPlayer class.

播放资产目录中的嵌入式音频文件

此代码在 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(); }

嗯,显然是方法签名

_mediaPlayer.SetDataSource(assetFileDescriptor); 

在后来的API中引入,(我在文档中找不到此方法签名在较低的API版本中无效)

但是方法签名

_mediaPlayer.SetDataSource(assetFileDescriptor.FileDescriptor, assetFileDescriptor.StartOffset, assetFileDescriptor.Length);

似乎有效 < API24

试试下面的代码,

_mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),assetFileDescriptor.getStartOffset(),assetFileDescriptor.getLength());