萬盛學電腦網

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

iOS 7 AVSpeechSynthesizer 打造有聲書應用:從零實現語音朗讀與翻頁同步

前言

iOS 7 引入 AVSpeechSynthesizer,讓 App 輕鬆實現文字轉語音 (TTS)。本教程基於官方範例專案,逐步構建一個可翻頁、自動朗讀的有聲書應用,涵蓋模型設計、手勢翻頁、語音合成器配置、語句隊列管理、語音委派回呼等完整流程。

專案架構概覽


Models:
  RWTBook       — 書籍容器,持有有序 Page 陣列
  RWTPage       — 頁面模型:displayText (朗讀文本) + backgroundImage (背景圖)

Presentation:
  RWTPageViewController — 視圖控制器:手勢翻頁、頁面顯示、語音朗讀協調

核心模型類別

RWTBook.h

@interface RWTBook : NSObject

@property (nonatomic, copy, readonly) NSArray *pages; // RWTPage 陣列

+ (instancetype)bookWithPages:(NSArray *)pages; // 指定頁面建立
+ (instancetype)testBook;                       // 測試用預設書籍

@end

RWTPage.h


extern NSString *const RWTPageAttributesKeyUtterances;      // 文本鍵
extern NSString *const RWTPageAttributesKeyBackgroundImage; // 背景圖鍵

@interface RWTPage : NSObject

@property (nonatomic, strong, readonly) NSString *displayText;
@property (nonatomic, strong, readonly) UIImage *backgroundImage;

+ (instancetype)pageWithAttributes:(NSDictionary *)attributes;

@end

視圖控制器基礎實現 (無語音版)


@interface RWTPageViewController ()
@property (nonatomic, strong) RWTBook *book;
@property (nonatomic, assign) NSUInteger currentPageIndex;
@end

@implementation RWTPageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupBook:[RWTBook testBook]];

    // 左滑 → 下一頁,右滑 → 上一頁
    UISwipeGestureRecognizer *swipeNext = [[UISwipeGestureRecognizer alloc]
        initWithTarget:self action:@selector(gotoNextPage)];
    swipeNext.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:swipeNext];

    UISwipeGestureRecognizer *swipePrev = [[UISwipeGestureRecognizer alloc]
        initWithTarget:self action:@selector(gotoPreviousPage)];
    swipePrev.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:swipePrev];
}

- (RWTPage *)currentPage {
    return self.book.pages[self.currentPageIndex];
}

- (void)setupBook:(RWTBook *)newBook {
    self.book = newBook;
    self.currentPageIndex = 0;
    [self setupForCurrentPage];
}

- (void)setupForCurrentPage {
    self.pageTextLabel.text = [self currentPage].displayText;
    self.pageImageView.image = [self currentPage].backgroundImage;
}

- (void)gotoNextPage {
    if (self.currentPageIndex + 1 < self.book.pages.count) {
        self.currentPageIndex++;
        [self setupForCurrentPage];
    }
}

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

整合 AVSpeechSynthesizer 實現自動朗讀

1. 匯入框架與宣告屬性


@import AVFoundation; // 模組化匯入 (iOS 7+)

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

2. 語音管理核心方法


#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; // 可選:實作 AVSpeechSynthesizerDelegate
    }
    [self speakNextUtterance];
}

3. 掛載至關鍵生命週期


- (void)viewDidLoad {
    // ... 既有代碼
    [self startSpeaking]; // 進入書籍即朗讀第一頁
}

- (void)gotoNextPage {
    // ... 既有翻頁邏輯
    [self startSpeaking]; // 翻頁後朗讀新頁面
}

- (void)gotoPreviousPage {
    // ... 既有翻頁邏輯
    [self startSpeaking];
}

4. 進階:實作 AVSpeechSynthesizerDelegate 實現逐字高亮/暫停/繼續


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

// 語句即將開始
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer
    willSpeakUtterance:(AVSpeechUtterance *)utterance {
    NSLog(@"開始朗讀: %@", utterance.speechString);
}

// 語句完成
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer
    didFinishUtterance:(AVSpeechUtterance *)utterance {
    NSLog(@"朗讀完成");
    // 可在此觸發自動翻頁、高亮清除等
}

// 語句暫停/繼續/取消
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer
    didPauseUtterance:(AVSpeechUtterance *)utterance {}
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer
    didContinueUtterance:(AVSpeechUtterance *)utterance {}
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer
    didCancelUtterance:(AVSpeechUtterance *)utterance {}

常見問題與優化

問題解決方案
無聲音檢查裝置音量、靜音開關、AVAudioSession 類別設為 AVAudioSessionCategoryPlayback
中文朗讀不自然指定 voiceWithLanguage:@"zh-TW" 或 zh-CN;iOS 9+ 支援增強版語音 (Enhanced)
長文本卡頓將長文本拆分為多個 AVSpeechUtterance (句子級),避免單一語句過長
背景播放啟用 Background Modes → Audio, AirPlay;設定 AVAudioSession 為 Playback 類別
打斷處理實作 AVAudioSessionInterruptionNotification 監聽來電、鬧鐘打斷,自動暫停/恢復

擴展功能建議

  1. 語速/音調控制 UI:Slider 調整 utterance.rate/pitchMultiplier
  2. 逐字高亮:使用 AVSpeechSynthesizerDelegate 的 willSpeakRangeOfSpeechString (iOS 13+) 同步高亮文本
  3. 書籤/進度同步:儲存 currentPageIndex + utterance.progress 至 iCloud/Core Data
  4. 多語言支援:根據書籍語言自動選擇對應 AVSpeechSynthesisVoice
  5. 離線語音包:引導用戶下載「增強版語音」獲得更自然語調
copyright © 萬盛學電腦網 all rights reserved