android mediaplayer SetDataSource(AssetFileDescriptor)不起作用<API 24

问题描述 投票:0回答:1

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

我的代码使用Android.Media.MediaPlayer类从assets目录中播放嵌入式音频文件。

此代码适用于API24及更高版本的设备。但它在mediaplayer.SetDataSource(assetFileDescriptor)上为API 23及更低版本的设备生成异常。

例外情况为“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
1个回答
0
投票

嗯显然是方法签名

_mediaPlayer.SetDataSource(assetFileDescriptor); 

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

但方法签名

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

似乎工作<API24

© www.soinside.com 2019 - 2024. All rights reserved.