Search code examples
swiftavaudioplayer

AudioPlayer (Swift) - play sound twice - with gap


I'm using the following code to play a sound file twice. The second sound plays immediately following the first

Is it possible to leave a time gap (1 second) between them? I've tried to find a solution reading the Apple Docs

var letterSound: AVAudioPlayer!

...


     @IBAction func speakLetter(sender: AnyObject) {

            let soundFile: String  = "SoundFile" + String(letterNumber)

            let path = Bundle.main.path(forResource: soundFile, ofType:"mp3")!
            let url = URL(fileURLWithPath: path)

            do {
                let sound = try AVAudioPlayer(contentsOf: url)
                letterSound = sound
                letterSound.numberOfLoops = 1
                letterSound.play()

            } catch {
                // couldn't load file :(
            }

        }

Solution

  • One option would be to add some 'white space' or silence at the end of your audio file.

    enter image description here

    If you don't have an audio editor i'd recommend Audacity, it's free and there are lots of tutorials on how to add silence.


    If you want a more code based option you could look in to using the AVAudioPlayerDelegate didFinishPlaying method to detect the end of the first play and then use play(atTime:) to trigger the next loop 1 second from now.

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        player.play(atTime: player.deviceCurrentTime + 1.0)
    }
    

    This code is untested and I think it might create an infinite loop so you may need some additional logic here to make sure it only loops once