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];
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)")
}
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)
}
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With