HOME > > 音声読み上げ(AVSpeechSynthesizer)再生後にバックグラウンドから復帰した以降音声読み上げしなくなる

音声読み上げ(AVSpeechSynthesizer)再生後にバックグラウンドから復帰した以降音声読み上げしなくなる

事象

テキストを音声読み上げしてくれるAVSpeechSynthesizerを使っているのですが、再生した後に新しい画面を表示し(バッググラウンド)になってからフォアグラウンドに戻ったあとは音声読み上げしてくれません。

func speech(_ sentence: String){
    let speechSynthesizer = AVSpeechSynthesizer()
    let utterance = AVSpeechUtterance(string: sentence)
    let voice = AVSpeechSynthesisVoice(language: "en-US")
    utterance.voice = voice
    utterance.volume = 1
    speechSynthesizer?.speak(utterance)
}

ちなみに、新しい画面では、iOS10から使えるようになったSpeech.frameworkで音声認識機能を実装しています。 この機能をオフにしたら、バックグラウンドからの復帰時に正常に音声読み上げが再生されます。

フォアグラウンドに復帰した後も音声読み上げが再生されるようにするためにはどうすればいいでしょうか。

回答

自己解決しました。どうやら、Speech.frameworkの音声認識を利用するときにAVAudioSessionaudioSessionRouteChangedのイベントが発生して音声読み上げに必要なAVAudioSessionCategoryが変更になり、再生しても音がでない状態になっているようです。

なので、音声認識させたあとにAVAudioSessionCategoryを元に戻す?処理を追加したら音がでるようになります。

override func viewWillDisappear(_ animated: Bool) {
    // AVSessionのカテゴリを変更
    let audioSession = AVAudioSession.sharedInstance()
    try! audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: .defaultToSpeaker)
    try! audioSession.setActive(true)
}

また、これだけだと通常のスピーカーで再生されないので、音声読み上げする直前にAVAudioSessionCategoryAVAudioSessionCategoryAmbientにしてあげると元の音量で再生されるようになります。

func speech(_ sentence: String){
    print("speech:(sentence)")

    // AVSessionのカテゴリを変更
    let audioSession = AVAudioSession.sharedInstance()
    try! audioSession.setCategory(AVAudioSessionCategoryAmbient)

    speechSynthesizer = AVSpeechSynthesizer()
    let utterance = AVSpeechUtterance(string: sentence)
    let voice = AVSpeechSynthesisVoice(language: "en-US")
    utterance.voice = voice
    utterance.volume = 1
    speechSynthesizer?.speak(utterance)
}

参考記事

http://nackpan.net/blog/2015/09/29/ios-swift-phone-call-and-route-change/

https://samekard.blogspot.jp/2014/12/avaudiosessionlate-2014_3.html

http://stackoverflow.com/questions/26478999/avspeechsynthesizer-stops-working-after-backgrounding

http://sarudeki.jp/matsuhouse/2012/06/11/iphone%E3%81%A7%E9%8C%B2%E9%9F%B3%E5%86%8D%E7%94%9F%E3%81%99%E3%82%8B/

-->