天天看點

Speech Synthesis(文字轉語音)

将文字轉換成語音.

Speech Synthesis

是作為一個管理iOS、iPadOS、tvOS、watchOS的語音和語音合成架構.如果要在macOS上使用文字轉語音,需要使用

NSSpeechSynthesizer

.

使用步驟:

  • 1.建立AVSpeechUtterance對象.(可以通過此定義一些比如說話速率之類的東西)
  • 2.将文字傳遞給

    AVSpeechSynthesizer

    對象來産生語音.

AVSpeechUtterance

可以了解為一句話.

AVSpeechSynthesisVoice

聲音有關(語言設定).

AVSpeechSynthesizer

可以了解為講述者.

示例

AVSpeechUtterance *speechUtterance = [[AVSpeechUtterance alloc] initWithString:@"what the fuck?"];
/// 播放語音速率(AVSpeechUtteranceMinimumSpeechRate - AVSpeechUtteranceMaximumSpeechRate)
speechUtterance.rate = AVSpeechUtteranceDefaultSpeechRate;
/// 基線音高(0.5 - 2. default 1.0)
speechUtterance.pitchMultiplier = 1.0;
/// 音量(0 - 1. default 1.0)
speechUtterance.volume = 1.0;
/// 下面兩個屬性是在一個`AVSpeechSynthesizer`執行個體的情況下,如果有多個`AVSpeechUtterance`執行個體在播放.每個`AVSpeechUtterance`執行個體播放間隔是`pre`+`post`之和.default 0
speechUtterance.preUtteranceDelay = 1.0;
speechUtterance.postUtteranceDelay = 1.0;
AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-Hant-CN"];
/// 設定發音
speechUtterance.voice = voice;
AVSpeechSynthesizer *speechSynthesizer = [[AVSpeechSynthesizer alloc] init];
[speechSynthesizer speakUtterance:speechUtterance];
           

AVSpeechSynthesizerDelegate

@protocol AVSpeechSynthesizerDelegate <NSObject>

@optional

/// 開始語音
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didStartSpeechUtterance:(AVSpeechUtterance *)utterance API_AVAILABLE(ios(7.0), watchos(1.0), tvos(7.0), macos(10.14));

/// 語音結束
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance API_AVAILABLE(ios(7.0), watchos(1.0), tvos(7.0), macos(10.14));

/// 語音暫停
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didPauseSpeechUtterance:(AVSpeechUtterance *)utterance API_AVAILABLE(ios(7.0), watchos(1.0), tvos(7.0), macos(10.14));

/// 語音繼續
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didContinueSpeechUtterance:(AVSpeechUtterance *)utterance API_AVAILABLE(ios(7.0), watchos(1.0), tvos(7.0), macos(10.14));

/// 語音取消
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didCancelSpeechUtterance:(AVSpeechUtterance *)utterance API_AVAILABLE(ios(7.0), watchos(1.0), tvos(7.0), macos(10.14));

/// 語音将要播放範圍
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer willSpeakRangeOfSpeechString:(NSRange)characterRange utterance:(AVSpeechUtterance *)utterance API_AVAILABLE(ios(7.0), watchos(1.0), tvos(7.0), macos(10.14));
@end
           

語音控制

typedef NS_ENUM(NSInteger, AVSpeechBoundary) {
    /// 立即停止
    AVSpeechBoundaryImmediate,
    /// 說完一整個單詞再停止
    AVSpeechBoundaryWord
} NS_ENUM_AVAILABLE(10_14, 7_0);

/// 停止
- (BOOL)stopSpeakingAtBoundary:(AVSpeechBoundary)boundary;
/// 暫停
- (BOOL)pauseSpeakingAtBoundary:(AVSpeechBoundary)boundary;
/// 繼續 	
- (BOOL)continueSpeaking;
           

繼續閱讀