10

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];
4

3 回答 3

15

在您的代码之前添加以下代码。您也可以在 appDelegate 中编写相同的代码。

NSError *setCategoryErr = nil;
NSError *activationErr  = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
[[AVAudioSession sharedInstance] setActive:YES error:&activationErr];
于 2014-08-15T15:20:27.220 回答
9

斯威夫特 3.0 答案

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)")
}
于 2016-10-10T20:49:04.343 回答
1

我有一个类似的问题,我通过添加 AVAudio 会话方法来修复。斯威夫特 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)
    
}
于 2020-10-25T05:36:59.867 回答