如何以 xamarin 形式连续播放音频

How to play audio continuously in xamarin forms

我实现了音频实现并添加了循环 属性。但音频仅播放两次,之后音频不播放。在这里我附上了我实现的代码。请帮助如何修复。感谢提前

namespace Com.Audio.Droid
{
    public class AudioService : IAudio
    {
        public AudioService()
        {
        }

        public void PlayAudioFile(string fileName)
        {
            var player = new MediaPlayer();
            var fd = global::Android.App.Application.Context.Assets.OpenFd("siren.wav");
            player.Prepared += (s, e) =>
            {
                player.Start();
            };
            player.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
            player.Looping = true;
            player.Prepare();
        }

        public void PauseAudioFile(string fileName)
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                var player = new MediaPlayer();
                var fd = global::Android.App.Application.Context.Assets.OpenFd("siren.wav");
                player.Prepared += (s, e) =>
                {
                    player.Stop();
                    player.Release();
                    player.Dispose();
                };
                player.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
                player.Prepare();
            });

        }
    }
}

而在 iOS 中,音频只播放了一秒钟。它没有完全播放音频文件

namespace com.Audio.ios
{
    public class AudioService : IAudio
    {
        public AudioService()
        {
        }

        public void PlayAudioFile(string fileName)
        {
            string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension("siren"), Path.GetExtension("siren.wav"));
            var url = NSUrl.FromString(sFilePath);
            var _player = AVAudioPlayer.FromUrl(url);
            _player.FinishedPlaying += (object sender, AVStatusEventArgs e) =>
            {
                _player = null;
            };
            _player.NumberOfLoops = -1;
            _player.Play();
        }

        public void PauseAudioFile(string fileName)
        {
            string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension("siren"), Path.GetExtension("siren.wav"));
            var url = NSUrl.FromString(sFilePath);
            var _player = AVAudioPlayer.FromUrl(url);
            _player.FinishedPlaying += (object sender, AVStatusEventArgs e) =>
            {
                _player = null;
            };
            _player.Stop();
        }
    }
}

对于Android

您需要一种挂钩方式来实现 loopMediaPlayer,即在音频结束时创建一个新播放器。

参考:.

对于iOS

由于ARC,可能AVAudioPlayer在调用依赖服务后被释放,要解决它你可以尝试将_player设为全局变量。

参考 .