11

I am using AVSpeechUtterance to Speak the given text. I am using the below code and works fine in 'iPhone Ringer Mode' but when I change the iPhone to 'Silent Mode' the utterance voice is getting mute. And when it is 'Silent Mode' I am unable to hear the utterance voice. What should I do to hear the utterance voice in 'Silent Mode'.

AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:@"Hello World"];
utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-US"];
[utterance setRate:AVSpeechUtteranceMinimumSpeechRate];
[utterance setVolume:1];
[self.speechSynthesizer speakUtterance:utterance];
Prashanth Rajagopalan
  • 718
  • 1
  • 10
  • 27

3 Answers3

16

Add the below code before your code. You can write the same code in appDelegate also.

NSError *setCategoryErr = nil;
NSError *activationErr  = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
[[AVAudioSession sharedInstance] setActive:YES error:&activationErr];
umakanta
  • 1,051
  • 19
  • 25
  • 1
    Hint: It seems like you must set the audio session category and activate the session before allocating your Speech Synthesizer. – John M. P. Knox Apr 30 '16 at 17:03
10

Swift 3.0 answer

do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
}
catch let error as NSError {
    print("Error: Could not set audio category: \(error), \(error.userInfo)")
}

do {
    try AVAudioSession.sharedInstance().setActive(true)
}
catch let error as NSError {
    print("Error: Could not setActive to true: \(error), \(error.userInfo)")
}
Danny
  • 3,975
  • 4
  • 22
  • 35
2

I had a similar issue and i fixed by adding AVAudio session method. Swift 5.0

    // this  AVAudioSession method is for speak text when device is in silent mode
    do {
        try AVAudioSession.sharedInstance().setCategory(.playback,mode: .default)

    } catch let error {
        print("This error message from SpeechSynthesizer \(error.localizedDescription)")
    }
    
    let speechSynthesizer = AVSpeechSynthesizer()
    let speechUtterance: AVSpeechUtterance = AVSpeechUtterance(string: text)
    
    speechUtterance.rate = AVSpeechUtteranceMaximumSpeechRate / 2.3
    speechUtterance.voice = AVSpeechSynthesisVoice(language: "en-US")
    speechSynthesizer.speak(speechUtterance)
    
}