0

I want to play sound at specific time, I used Method PlayAtTime on AVAudioPlayerNode this is my code:

 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}");
        }
    }

but the code does not working. The audio is always start from beginning.

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
onlyme
  • 21
  • 4

1 Answers1

0

Your PlayAtTime needs to be based upon the audio player instance(s) that you are delaying and/or sync'ing together.

Obtain the current time from AVAudioPlayer.DeviceCurrentTime and add the number of seconds (double based) in the future that you wish to start the player:

Example:

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
Community
  • 1
  • 1
SushiHangover
  • 73,120
  • 10
  • 106
  • 165
  • thanks for answer my question, i already try like that, but the audio is not playing, i can't hear the audio – onlyme May 09 '17 at 04:44
  • @HarizalHilmi If you just call the `Play()` method instead of `PlayAtTime()`, does that work? – SushiHangover May 09 '17 at 04:50
  • yes, and if i use my code above, the audio is playing but, always start at begining,, – onlyme May 09 '17 at 08:37
  • @HarizalHilmi `always start at beginning` ? `PlayAtTime` is a delay to start playing the audio at a future time, it is not a time within the audio timeline. `AVAudioPlayer` has a `CurrentTime` Property that you can set if you are looking to seek to a different time within the audio – SushiHangover May 09 '17 at 08:54