当铃声静音时,使iOS文本到语音工作

时间:2017-06-03 12:19:45

标签: ios objective-c text-to-speech

我以非常标准的方式调用iOS文本到语音:

static AVSpeechSynthesizer* synthesizer = NULL;
//...
+(void)readText:(NSString*)text
{
    if(synthesizer == NULL)
    synthesizer = [[AVSpeechSynthesizer alloc] init];
    AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:text];
    utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"fr-FR"];
    [synthesizer speakUtterance:utterance];
}

它完成了这项工作,除了一个问题:当铃声在设备上静音时,文本到语音也被静音。即使振铃器静音,我该如何使它工作?

3 个答案:

答案 0 :(得分:1)

取消设备取消静音

static AVSpeechSynthesizer* synthesizer = NULL;
//...
+(void)readText:(NSString*)text
{
    if(synthesizer == NULL)
    synthesizer = [[AVSpeechSynthesizer alloc] init];
    AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:text];
    utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"fr-FR"];

    //Add the following code to active audio
    NSError *setCategoryErr = nil;
    NSError *activationErr  = nil;
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
    //magic is here
    [[AVAudioSession sharedInstance] setActive:YES error:&activationErr]; 

    //speech your text
    [synthesizer speakUtterance:utterance];
}

答案 1 :(得分:1)

iOS音频会话类别是正确答案:https://developer.apple.com/library/content/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/AudioSessionCategoriesandModes/AudioSessionCategoriesandModes.html

默认值为AVAudioSessionCategorySoloAmbient,但如果音频功能是应用程序的核心(我们的情况),则应将其设置为AVAudioSessionCategoryPlayback

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

答案 2 :(得分:0)

感谢Leo Cavalcante。设置AVAudioSession setCategory等之后,它解决了我的问题。

我在下面添加了快速代码。

do {
        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
        try AVAudioSession.sharedInstance().setActive(true)
       // try AVAudioSession.sharedInstance().overrideOutputAudioPort(.speaker)
    } catch let error as NSError {
        print("audioSession error: \(error.localizedDescription)")
    }