iOS開發日記50-文本轉語音(TTS),50-tts
今天博主有一個文本轉語音(TTS)的需求,遇到了一些困痛點,在此和大家分享,希望能夠共同進步.
文本轉語音技術, 也叫TTS, 是Text To Speech的縮寫. iOS如果想做有聲書等功能的時候, 會用到這門技術.
iOS7之後才有該功能,需要匯入 AVFoundation 庫
//在iPhone靜音開啟後,聲音無法播放,需要開啟後台播放
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
//語音合成器, 是最主要的介面
AVSpeechSynthesizer *av = [[AVSpeechSynthesizer alloc]init];
//要說的一段話,語音合成器的播放內容介面
AVSpeechUtterance *utterance1 = [[AVSpeechUtterance alloc]initWithString:[NSString stringWithFormat:@"%@",@"即時"]]; //需要轉換的文本
//讀完一段後的停頓時間
utterance1.postUtteranceDelay=0.1;
//說話的速率
utterance1.rate=0.4;
//開始播放內容
[av speakUtterance:utterance1];
AVSpeechSynthesisVoice定義了一系列的聲音, 主要是不同的語言和地區.下面是他的幾個屬性和方法
voiceWithLanguage: 根據制定的語言, 獲得一個聲音.
speechVoices: 獲得當前裝置支援的聲音
currentLanguageCode: 獲得當前聲音的語言字串, 比如”ZH-cn”
language: 獲得當前的語言
上面是一段簡單的TTS播放,如果想要進行更複雜的操作,可以遵守AVSpeechSynthesizerDelegate協議,實現其方法
合成器的委託, 對於一些事件, 提供了響應的介面.
didCancelSpeechUtterance: 已經取消說話
didContinueSpeechUtterance: 已經繼續說話
didFinishSpeechUtterance: 已經說完
didPauseSpeechUtterance: 已經暫停
didStartSpeechUtterance:已經開始
willSpeakRangeOfSpeechString:將要說某段話