Search code examples
iosswiftairplayavspeechsynthesizer

AVSpeechSynthesizer and AirPlay — Audio Device Sleeping?


If I use AVSpeechSynthesizer to speak some text it works fine on the device but as soon as I use AirPlay the start of the speech will get cut off unless something was just spoken before.

It appears that the audio device is going to sleep.

Below is my code

let synthesizer = AVSpeechSynthesizer()

func speakCall(call: (letter: String, number: Int)) -> Void {
    for  _ in 1...2 { // Speak the message twice
        let utterance = AVSpeechUtterance(string: "\(call.letter), \(call.number)")
        utterance.postUtteranceDelay = 0.15
        synthesizer.speakUtterance(utterance)
    }
}

Solution

  • You can tell AVAudioPlayer to play silence, that will cause the audio device to not sleep.

    let silence = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("silence", ofType: "mp3")!)
    var silencePlayer: AVAudioPlayer?
    try? silencePlayer = AVAudioPlayer(contentsOfURL: silence)
    silencePlayer?.numberOfLoops = -1
    silencePlayer?.play()