- 写在前面,该单类来自于高德地图demo,我只是分享出来方便大家使用而已。简单的语音合合成够用了
- 大家可以对我上一篇关于语音合成的文章看,我那个代码就当做反例吧。
上代码
//
// SpeechSynthesizer.h
// AMapNaviKit
//
// Created by 刘博 on 16/4/1.
// Copyright © 2016年 AutoNavi. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <AVFoundation/AVSpeechSynthesis.h>
/**
* iOS7及以上版本可以使用 AVSpeechSynthesizer 合成语音
*
* 或者采用"科大讯飞"等第三方的语音合成服务
*/
@interface SpeechSynthesizer : NSObject
+ (instancetype)sharedSpeechSynthesizer;
- (void)speakString:(NSString *)string;
- (void)stopSpeak;
@end
//
// SpeechSynthesizer.m
// AMapNaviKit
//
// Created by 刘博 on 16/4/1.
// Copyright © 2016年 AutoNavi. All rights reserved.
//
#import "SpeechSynthesizer.h"
@interface SpeechSynthesizer () <AVSpeechSynthesizerDelegate>
@property (nonatomic, strong, readwrite) AVSpeechSynthesizer *speechSynthesizer;
@end
@implementation SpeechSynthesizer
+ (instancetype)sharedSpeechSynthesizer
{
static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[SpeechSynthesizer alloc] init];
});
return sharedInstance;
}
- (instancetype)init
{
if (self = [super init])
{
[self buildSpeechSynthesizer];
}
return self;
}
- (void)buildSpeechSynthesizer
{
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0)
{
return;
}
self.speechSynthesizer = [[AVSpeechSynthesizer alloc] init];
[self.speechSynthesizer setDelegate:self];
}
- (void)speakString:(NSString *)string
{
if (self.speechSynthesizer)
{
AVSpeechUtterance *aUtterance = [AVSpeechUtterance speechUtteranceWithString:string];
[aUtterance setVoice:[AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"]];
//iOS语音合成在iOS8及以下版本系统上语速异常
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0)
{
aUtterance.rate = 0.25;//iOS7设置为0.25
}
else if ([[[UIDevice currentDevice] systemVersion] floatValue] < 9.0)
{
aUtterance.rate = 0.15;//iOS8设置为0.15
}
if ([self.speechSynthesizer isSpeaking])
{
[self.speechSynthesizer stopSpeakingAtBoundary:AVSpeechBoundaryWord];
}
[self.speechSynthesizer speakUtterance:aUtterance];
}
}
- (void)stopSpeak
{
if (self.speechSynthesizer)
{
[self.speechSynthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
}
}
@end
- 首先,语音合成明显可以写成一个单类。
大多数情况我们根本就没有意识到一个类是否有必要写成单类
- 虽然现在觉大部分用户的系统都在7.0以上,不过下面这个判断真是个好习惯
- (void)buildSpeechSynthesizer
{
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0)
{
//虽然现在觉大部分用户的系统都在7.0以上,不过这个判断真是个好习惯
return;
}
self.speechSynthesizer = [[AVSpeechSynthesizer alloc] init];
[self.speechSynthesizer setDelegate:self];
}
- 再啰嗦一句,漂亮的代码看上去就是爽啊
2017-05-08 迟到的demo 我给你们补上了
-
点击下载demo
你看大半年过去了我还记得上传demo,不给个star鼓励下我么