避免在Xamarinn Forms Android上播放音频时使用过时的Forms.Context

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

如何使用Xamarin Forms在Android上播放音频?我有以下服务,但是可以使用,但是Forms.Context不再支持,消息为“上下文从版本2.5开始已过时。请改用本地上下文。”。

[assembly: Dependency(typeof(AudioService))]
namespace SensaLabScan.Droid.Services
{
    public class AudioService : IAudioService
    {
        private readonly MediaPlayer _mediaPlayer = new MediaPlayer();

        public void PlayBeep()
        {
            _mediaPlayer.Reset();

            // Forms.Context references the Activity which calls Forms.Init, i.e. MainActivity.
            using (var beepFile = Forms.Context.Assets.OpenFd("beep.mp3"))
            {
                _mediaPlayer.SetDataSource(beepFile);
                _mediaPlayer.Prepare();
                _mediaPlayer.Start();
            }
        }
    }
}

在这种情况下,替代已弃用的Forms.Context有什么选择?我已经尝试过

  1. [Android.App.Application.Context.Assets.OpenFd("beep.pm3");,但这会引发文件未找到异常
  2. 使用MainActivity作为上下文,并从中使用Assets,但仍然是找不到文件错误。

我要阅读的mp3文件位于Assets文件夹中,并标记为AndroidAsset

android xamarin xamarin.forms xamarin.android
1个回答
0
投票
这是使用DependenceService播放音频的代码。

[assembly: Dependency(typeof(MyDependenceService))] namespace MediaPlayDemo.Droid { public class MyDependenceService : IPlayMedia { public void playMusic() { //throw new NotImplementedException(); var bytes = default(byte[]); using (StreamReader reader = new StreamReader(Android.App.Application.Context.Assets.Open("Test.mp3"))) { using (var memstream = new MemoryStream()) { reader.BaseStream.CopyTo(memstream); bytes = memstream.ToArray(); } } Play(bytes); } // Stop(); MediaPlayer currentPlayer; public void Play(byte[] AudioFile) { Stop(); currentPlayer = new MediaPlayer(); currentPlayer.Prepared += (sender, e) => { currentPlayer.Start(); }; currentPlayer.SetDataSource(new StreamMediaDataSource(new System.IO.MemoryStream(AudioFile))); currentPlayer.Prepare(); } void Stop() { if (currentPlayer == null) return; currentPlayer.Stop(); currentPlayer.Dispose(); currentPlayer = null; } } public class StreamMediaDataSource : MediaDataSource { System.IO.Stream data; public StreamMediaDataSource(System.IO.Stream Data) { data = Data; } public override long Size { get { return data.Length; } } public override int ReadAt(long position, byte[] buffer, int offset, int size) { data.Seek(position, System.IO.SeekOrigin.Begin); return data.Read(buffer, offset, size); } public override void Close() { if (data != null) { data.Dispose(); data = null; } } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (data != null) { data.Dispose(); data = null; } } } }

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