【问题标题】:android mediaplayer SetDataSource(AssetFileDescriptor) does not work < API 24android mediaplayer SetDataSource(AssetFileDescriptor) 不起作用 < API 24
【发布时间】: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


    【解决方案1】:

    试试下面的代码,

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

    【讨论】:

      【解决方案2】:

      嗯显然是方法签名

      _mediaPlayer.SetDataSource(assetFileDescriptor); 
      

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

      但是方法签名

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

      似乎有效

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-17
        相关资源
        最近更新 更多