萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

iOS 有聲書應用開發實戰:AVSpeechSynthesizer 語音合成完整實現

前言

本文系統講解如何使用 iOS 7 引入的 AVSpeechSynthesizer 框架,構建一個具備翻頁同步朗讀、語音控制、代理回呼處理的有聲書應用。內容涵蓋模型層設計、視圖控制器邏輯、語音合成器初始化與配置、多語言語音選擇、背景播放設定及常見問題排查。

專案架構設計

模型層

  • RWTBook:書籍容器,持有有序的 RWTPage 陣列,提供 testBook 快速建立測試資料
  • RWTPage:單頁模型,包含 displayText (朗讀文本) 與 backgroundImage (背景圖片),支援字典初始化

表現層

  • RWTPageViewController:管理頁面顯示、手勢翻頁 (左右滑動)、語音朗讀協調
  • 內部狀態:book、currentPageIndex、synthesizer

核心實現步驟

1. 導入 AVFoundation 框架

@import AVFoundation; // 模組化導入,自動連結框架

2. 宣告語音合成器屬性


@interface RWTPageViewController ()
@property (nonatomic, strong) AVSpeechSynthesizer *synthesizer;
// ... 既有屬性
@end

3. 實現語音朗讀邏輯


#pragma mark - Speech Management

// 建立並朗讀當前頁面語句
- (void)speakNextUtterance {
    NSString *text = [self currentPage].displayText;
    if (text.length == 0) return;

    AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:text];
    // 語音配置
    utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-TW"]; // 繁體中文
    utterance.rate = AVSpeechUtteranceDefaultSpeechRate; // 0.0~1.0
    utterance.pitchMultiplier = 1.0;
    utterance.volume = 1.0;

    [self.synthesizer speakUtterance:utterance];
}

// 確保合成器存在並啟動朗讀
- (void)startSpeaking {
    if (!self.synthesizer) {
        self.synthesizer = [[AVSpeechSynthesizer alloc] init];
        self.synthesizer.delegate = self; // 可選:處理進度回呼
    }
    [self speakNextUtterance];
}

4. 整合至翻頁流程


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupBook:[RWTBook testBook]];
    // ... 手勢設定
    [self startSpeaking]; // 進入即朗讀第一頁
}

- (void)gotoNextPage {
    if (self.currentPageIndex + 1 < self.book.pages.count) {
        self.currentPageIndex++;
        [self setupForCurrentPage];
        [self startSpeaking]; // 翻頁後朗讀新頁
    }
}

- (void)gotoPreviousPage {
    if (self.currentPageIndex > 0) {
        self.currentPageIndex--;
        [self setupForCurrentPage];
        [self startSpeaking];
    }
}

5. 實作 AVSpeechSynthesizerDelegate (進階控制)


@interface RWTPageViewController () 
// ...
@end

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer
    willSpeakUtterance:(AVSpeechUtterance *)utterance {
    // 可在此更新 UI:顯示「正在朗讀...」、高亮當前句子
}

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer
    didFinishUtterance:(AVSpeechUtterance *)utterance {
    // 朗讀結束:可自動翻頁、儲存進度、釋放資源
}

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer
    didPauseUtterance:(AVSpeechUtterance *)utterance {
    // 來電、鬧鐘打斷
}

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer
    didContinueUtterance:(AVSpeechUtterance *)utterance {
    // 恢復播放
}

關鍵配置與優化

音訊會話設定 (支援背景播放、鎖屏控制)


- (void)configureAudioSession {
    NSError *error = nil;
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback
                 withOptions:AVAudioSessionCategoryOptionMixWithOthers
                       error:&error];
    [session setActive:YES error:&error];
    // 註冊遠端控制事件 (耳機線控、鎖屏控制中心)
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}

語音選擇最佳實踐


// 列出所有可用中文語音
NSArray *voices = [AVSpeechSynthesisVoice speechVoices];
for (AVSpeechSynthesisVoice *v in voices) {
    if ([v.language hasPrefix:@"zh"]) {
        NSLog(@"語音: %@, 品質: %@, 識別碼: %@", v.name, v.quality, v.identifier);
    }
}
// 選擇 Enhanced 品質語音 (需用戶預先下載)
AVSpeechSynthesisVoice *preferred = [AVSpeechSynthesisVoice voiceWithIdentifier:@"com.apple.ttsbundle.Mei-Jia_premium"];

長文本分段策略

單一 AVSpeechUtterance 過長會導致啟動延遲與記憶體壓力。建議按句號/換行拆分:


- (NSArray *)utterancesForText:(NSString *)text {
    NSMutableArray *utterances = [NSMutableArray array];
    NSArray *sentences = [text componentsSeparatedByCharactersInSet:
        [NSCharacterSet characterSetWithCharactersInString:@".。\n"]];
    for (NSString *sentence in sentences) {
        sentence = sentence.stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if (sentence.length > 0) {
            AVSpeechUtterance *u = [[AVSpeechUtterance alloc] initWithString:sentence];
            u.voice = self.synthesizer.voice; // 繼承語音設定
            [utterances addObject:u];
        }
    }
    return utterances;
}

測試與除錯

  • 模擬器無聲:Mac 系統音量、模擬器 Hardware → Audio Output 確認
  • 真機無聲:檢查靜音鍵、音量、AVAudioSession 類別、是否被其他 App 佔用音訊焦點
  • 主控台噪音:模擬器可能輸出大量 AudioHardware 相關日誌,屬正常現象

總結

AVSpeechSynthesizer 為 iOS 應用提供了強大且易用的離線 TTS 能力。透過合理的模型設計、語句隊列管理、代理回呼處理與音訊會話配置,可快速構建高品質的有聲書、導航播報、無障礙輔助等語音應用。配合 iOS 13+ 的 willSpeakRangeOfSpeechString 更能實現精準的逐字高亮,大幅提升用戶體驗。

copyright © 萬盛學電腦網 all rights reserved