Search code examples
swiftavaudioengineavaudioplayernode

AVAudoPlayerNode to play a sound for a defined number of times


Is it possible in AVAudioPlayerNode to loop an audio sound for a number of times only instead of infinite times? The below code scheduled the audio for an infinite number of times instead of saying 5 times.

aVAudioPlayerNode.scheduleBuffer(buffer!, at: nil, options: AVAudioPlayerNodeBufferOptions.loops, completionHandler: nil)

I am looking similar as AVAudioPlayer's as numberOfLoops to define how many times to play an audio. I could use AVAudioPlayer but there is no functionality to play with audio pitch.


Solution

  • The scheduleBuffer documentation says "Schedules the buffer to be played following any previously scheduled commands.". So just schedule it multiple times.

    extension AVAudioPlayerNode {
        func sceduleBuffer(_ buffer: AVAudioPCMBuffer, numberOfLoops: Int = 1) {
            for _ in 0..<numberOfLoops { scheduleBuffer(buffer, at: nil) }
        }
    }