0

我想在特定时间播放声音,我使用了方法PlayAtTimeAVAudioPlayerNode 这是我的代码:

 private AVAudioUnitReverb reverb;
 private AVAudioEngine engine;
 private AVAudioFile file;
 private AVAudioPlayerNode audioPlayerNode;

 public void PlayBackgroundMusic(byte[] data, string extention, string filename, double playingAt)
    {
        try
        {
            NSError err;
            engine = new AVAudioEngine();
            audioPlayerNode = new AVAudioPlayerNode();
            engine.AttachNode(audioPlayerNode);

            filename = filename.Replace(@"/", @"%2F").Replace(" ", @"%20");
            NSUrl url = new NSUrl(filename);
            file = new AVAudioFile(url, out err);

            reverb = new AVAudioUnitReverb();
            reverb.LoadFactoryPreset(AVAudioUnitReverbPreset.SmallRoom);

            engine.AttachNode(reverb);

            ConnectAudioNodes(audioPlayerNode, /*timePitch,*/ reverb, engine.OutputNode);

            audioPlayerNode.Stop();                

            engine.StartAndReturnError(out err);
            var hostTime = AVAudioTime.HostTimeForSeconds(playingAt);
            audioPlayerNode.ScheduleFile(file, new AVAudioTime(hostTime), null);
            audioPlayerNode.PlayAtTime(new AVAudioTime(hostTime));                   

            backgroundSong = filename;
        }
        catch (Exception ex)
        {
            MetricsManager.TrackEvent($"AudioService.PlayBackgroundMusic error {ex.Message}");
        }
    }

但代码不起作用。音频总是从头开始。

4

1 回答 1

0

PlayAtTime需要基于您正在延迟和/或同步的音频播放器实例。

获取当前时间AVAudioPlayer.DeviceCurrentTime添加您希望启动播放器的未来秒数(基于双倍):

例子:

var player1 = AVAudioPlayer.FromUrl(new NSUrl("FireplaceWoodCrackle.mp3", ""), out NSError nsError);
Debug.WriteLine(nsError?.Description);
if (nsError == null)
    player1.PlayAtTime(player1.DeviceCurrentTime + 10); // play at 10 seconds in the future
于 2017-05-08T21:04:26.240 回答