我想在特定时间播放声音,我使用了方法PlayAtTime
,AVAudioPlayerNode
这是我的代码:
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}");
}
}
但代码不起作用。音频总是从头开始。