惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

雷峰网
雷峰网
MongoDB | Blog
MongoDB | Blog
D
Docker
Martin Fowler
Martin Fowler
人人都是产品经理
人人都是产品经理
GbyAI
GbyAI
Jina AI
Jina AI
酷 壳 – CoolShell
酷 壳 – CoolShell
M
MIT News - Artificial intelligence
腾讯CDC
阮一峰的网络日志
阮一峰的网络日志
H
Hackread – Cybersecurity News, Data Breaches, AI and More
N
Netflix TechBlog - Medium
B
Blog RSS Feed
云风的 BLOG
云风的 BLOG
Blog — PlanetScale
Blog — PlanetScale
Vercel News
Vercel News
The Cloudflare Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
有赞技术团队
有赞技术团队
G
Google Developers Blog
Stack Overflow Blog
Stack Overflow Blog
I
InfoQ
U
Unit 42

少数派

派早报:Google 发布 Fitbit Air 等 - 少数派 「新人报到」確認需求,再開始 - 少数派 从 SOLO 独立开发者社区,我看到了越来越多开发者开始做自己的产品 - 少数派 我怎么管理那些"不常做,但总会忘"的生活事项 - 少数派 人形机器人量产元年,数据才是具身智能的“生死线” - 少数派 BuhoLaunchpad 高度还原 Mac 启动台:开发历程与思考 - 少数派 五年陪伴依然不舍,DIY 换壳后让罗技 MX Master 3 继续服役 - 少数派 新玩意 240|少数派的编辑们最近买了啥? - 少数派 一日一技|为什么你应该关闭 iOS 的键盘声音 - 少数派 我做了个插件和 Skills,一键提取任何网站的设计规范 Design.md - 少数派 住在三四线城市的你,该开始录播客了 - 少数派 甘南秘境,大白高国 - 少数派 AI的审美:谁让把我变成川内倫子 - 少数派 返工怎能不烦恼,打工人片单总有一部是你的「嘴替」 - 少数派 为了让「上厕所」更健康,我做了一个小工具 - 少数派 AI + Skill,能够让生成的文章去除 AI 味吗? - 少数派 新玩意|韶音OpenDots ONE 耳夹式耳机 - 少数派 《美满》| 在每一个春天的晚上相爱(362) - 少数派 新玩意|优篮子 PS01 MagSnap 磁吸支架 - 少数派 自我整合手记 | 我开始早睡了:用稳定规则,为自由托底 - 少数派 用龙虾(OpenClaw)两个多月,我最深的12个体会 - 少数派 听歌时间到,12 张你可能错过的 2025 华语乐坛好专辑 - 少数派 承诺能追吗 - 少数派 macOS 26启动台没了? 我做了个不一样的App启动器 - Keboard - 少数派 《四海为家的人》| INTJ对话INTJ(361) - 少数派 你发过的那些黑历史,是时候一次清干净了 - 少数派 新玩意:安安静静玩,越玩越专注:计客密码机 - 少数派 iPad 用户首次体验 Android 平板:vivo Pad6 Pro - 少数派 数据逻辑强 - 少数派 极北行+ | 一路向北,探访日本至北之地 | 001 - 少数派
iOS基于AVFoundation实现朗读文字 - 少数派
2021-08-19 · via 少数派

iOS基于AVFoundation实现朗读文字

##1.心理建设
众所周知AVFoundation的朗读是个智障语气,所以想不花钱就只能忍着。
##2.speechManager

@import AVFoundation;

@protocol TJSpeechManagerDelegate <NSObject>
@optional
- (void)didStartSpeechUtterance:(AVSpeechUtterance*)utterance;
- (void)didFinishSpeechUtterance:(AVSpeechUtterance*)utterance;
- (void)didPauseSpeechUtterance:(AVSpeechUtterance*)utterance;
- (void)didCancelSpeechUtterance:(AVSpeechUtterance*)utterance;
- (void)willSpeakRangeOfSpeechString:(NSRange)characterRange utterance:(AVSpeechUtterance *)utterance;

- (void)needRepeatSpeech:(AVSpeechUtterance *)utterance;
@end

@interface TJSpeechManager : NSObject <AVSpeechSynthesizerDelegate>


@property (nonatomic, strong) AVSpeechSynthesizer *avSpeech;
@property (nonatomic, strong) AVSpeechUtterance *speechUtt;

@property (nonatomic, assign) id <TJSpeechManagerDelegate> delegate;


- (void)setSpeechContent:(NSString *)content;


- (void)pauseSpeech;


- (void)beginSpeech;

- (void)continueSpeech;

- (void)endSpeech;

@end


#import "TJSpeechManager.h"

@implementation TJSpeechManager

- (void)setSpeechContent:(NSString *)content {
    AVSpeechUtterance *speechUtt = [AVSpeechUtterance speechUtteranceWithString:content];
    speechUtt.rate = 0.5;
    speechUtt.pitchMultiplier = 1;

    //设置音量,[0-1] 默认 = 1
    speechUtt.volume = 1;

    //读一段前的停顿时间
    speechUtt.preUtteranceDelay = 1;
    //读完一段后的停顿时间
    speechUtt.postUtteranceDelay = 1;
    AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
    speechUtt.voice = voice;
    self.speechUtt = speechUtt;
}

- (void)beginSpeech {
    //这里需要注意一下,一个avspeech对象只能播放一次,同一个对象中途不能重新播放。
    AVSpeechSynthesizer *avSpeech = [[AVSpeechSynthesizer alloc] init];
    avSpeech.delegate = self;
    [avSpeech speakUtterance:self.speechUtt];
    self.avSpeech = avSpeech;
}

- (void)pauseSpeech {
    [self.avSpeech pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];
}

- (void)continueSpeech {
    if(self.avSpeech.isPaused) {
        [self.avSpeech continueSpeaking];
        [NSThread sleepForTimeInterval:0.25f];
    }
}

- (void)endSpeech {
    if(self.avSpeech.isSpeaking) {
        [self.avSpeech stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
        [NSThread sleepForTimeInterval:0.25f];
    }
}

//代理主要是返回给controller,用来和UI交互
#pragma mark - AVSpeechSynthesizerDelegate;
- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didStartSpeechUtterance:(AVSpeechUtterance*)utterance{
    NSLog(@"---开始播放");
    if(self.delegate && [self.delegate respondsToSelector:@selector(didStartSpeechUtterance:)]) {
        [self.delegate didStartSpeechUtterance:utterance];
    }
}

- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance*)utterance{
    NSLog(@"---完成播放");
    if(self.delegate && [self.delegate respondsToSelector:@selector(didFinishSpeechUtterance:)]) {
        [self.delegate didFinishSpeechUtterance:utterance];
    }
}

- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didPauseSpeechUtterance:(AVSpeechUtterance*)utterance{
    NSLog(@"---播放中止");
    if(self.delegate && [self.delegate respondsToSelector:@selector(didPauseSpeechUtterance:)]) {
        [self.delegate didPauseSpeechUtterance:utterance];
    }
}

- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didContinueSpeechUtterance:(AVSpeechUtterance*)utterance{
    NSLog(@"---恢复播放");

}

- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didCancelSpeechUtterance:(AVSpeechUtterance*)utterance{
    NSLog(@"---播放取消");
    if(self.delegate && [self.delegate respondsToSelector:@selector(didCancelSpeechUtterance:)]) {
        [self.delegate didCancelSpeechUtterance:utterance];
    }
}

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer willSpeakRangeOfSpeechString:(NSRange)characterRange utterance:(AVSpeechUtterance *)utterance {
    if(self.delegate && [self.delegate respondsToSelector:@selector(willSpeakRangeOfSpeechString:utterance:)]) {
        [self.delegate willSpeakRangeOfSpeechString:characterRange utterance:utterance];
    }
}

@end

##3.使用范例

//分页控制器获取到当前页内容
-(void)pageReadViewControllerSpeechContent:(NSString *)content
{
//先停止语音 防止用户翻页造成声音重叠
    [self.speechManager endSpeech];
    //当期是否开启了朗读功能
    if (self.isSpeechNextPage == YES ) {
    //内容不为空 代表可以朗读下一页
        if ( content && content.length > 0) {
        //设置朗读内容
            [self.speechManager setSpeechContent:content];
            //开始朗读
            [self.speechManager beginSpeech];
        }else{
            self.isSpeechNextPage = NO;
            [self.speechManager endSpeech];
        }
    }
}

///朗读按钮开启
-(void)readMenuDidOpenSpeechRead
{
    self.isSpeechNextPage = YES;
    //用于刷新当前页内容 从而调用pageReadViewControllerSpeechContent
    [self speechNextPage:self.book.page];
}
//用户关闭朗读
-(void)readMenuDidCloseSpeechRead
{
    [self.speechManager pauseSpeech];
    self.isSpeechNextPage = NO;
}
//当前页内容读完
- (void)didFinishSpeechUtterance:(AVSpeechUtterance *)utterance
{
    //我这里的逻辑是用于控制翻页还是下一章
        //下一章或者下一页都会重绘pageViewControl内容 从而继续响应 pageReadViewControllerSpeechContent 的回调代理
    if ([TJReadRecordManager recordWithBookId:self.book.bookId].page + 2 > [TJReadRecordManager recordWithBookId:self.book.bookId].chapter.pageModels.count) {

        [self readMenuDidChangeChapter:YES];
    }else{
        [self speechNextPage:[TJReadRecordManager recordWithBookId:self.book.bookId].page + 1];
    }
}

##4.简单使用
如果各位想简单应用一下
初始化 manager

-(TJSpeechManager *)speechManager
{
    if (!_speechManager) {
        _speechManager = [[TJSpeechManager alloc]init];
        _speechManager.delegate = self;
    }
    return _speechManager;
}

然后直接开始朗读就行了


      [self.speechManager setSpeechContent:@"想说的话"];
            //开始朗读
            [self.speechManager beginSpeech];

##5.退出
退出页面记得停止播放

-(void)dealloc
{
    self.speechManager.delegate = nil;

    [self.speechManager endSpeech];
}

附上APP地址: 一阅阅读有想看小说的小伙伴可以试下 支持换源 支持自定义书源