无声模式下的言语



我正在使用AVSpeechUtterance来说出给定的文本。我使用下面的代码,并在"iPhone铃声模式"下工作良好,但当我将iPhone更改为"静音模式"时,说话的声音变得静音。当它处于"静音模式"时,我听不到说话的声音。在"静音模式"下,我该怎么做才能听到说话的声音?

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

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

NSError *setCategoryErr = nil;
NSError *activationErr  = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
[[AVAudioSession sharedInstance] setActive:YES error:&activationErr];

Swift 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)")
}

我有一个类似的问题,我通过添加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)
    
}

最新更新