Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVSpeechUtterance utterance voice in silent mode

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];
like image 890
Prashanth Rajagopalan Avatar asked Aug 03 '14 13:08

Prashanth Rajagopalan


3 Answers

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)")
}
like image 198
Danny Avatar answered Oct 14 '22 11:10

Danny


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)
    
}
like image 39
Dambar B. Bista Avatar answered Oct 14 '22 10:10

Dambar B. Bista


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];
like image 42
umakanta Avatar answered Oct 14 '22 11:10

umakanta