- 寫在前面,該單類來自于高德地圖demo,我只是分享出來方便大家使用而已。簡(jiǎn)單的語音合合成夠用了
- 大家可以對(duì)我上一篇關(guān)于語音合成的文章看,我那個(gè)代碼就當(dāng)做反例吧。
上代碼
//
// 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 合成語音
*
* 或者采用"科大訊飛"等第三方的語音合成服務(wù)
*/
@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及以下版本系統(tǒng)上語速異常
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0)
{
aUtterance.rate = 0.25;//iOS7設(shè)置為0.25
}
else if ([[[UIDevice currentDevice] systemVersion] floatValue] < 9.0)
{
aUtterance.rate = 0.15;//iOS8設(shè)置為0.15
}
if ([self.speechSynthesizer isSpeaking])
{
[self.speechSynthesizer stopSpeakingAtBoundary:AVSpeechBoundaryWord];
}
[self.speechSynthesizer speakUtterance:aUtterance];
}
}
- (void)stopSpeak
{
if (self.speechSynthesizer)
{
[self.speechSynthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
}
}
@end
- 首先,語音合成明顯可以寫成一個(gè)單類。
大多數(shù)情況我們根本就沒有意識(shí)到一個(gè)類是否有必要寫成單類
- 雖然現(xiàn)在覺大部分用戶的系統(tǒng)都在7.0以上,不過下面這個(gè)判斷真是個(gè)好習(xí)慣
- (void)buildSpeechSynthesizer
{
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0)
{
//雖然現(xiàn)在覺大部分用戶的系統(tǒng)都在7.0以上,不過這個(gè)判斷真是個(gè)好習(xí)慣
return;
}
self.speechSynthesizer = [[AVSpeechSynthesizer alloc] init];
[self.speechSynthesizer setDelegate:self];
}
- 再啰嗦一句,漂亮的代碼看上去就是爽啊
2017-05-08 遲到的demo 我給你們補(bǔ)上了
-
點(diǎn)擊下載demo
你看大半年過去了我還記得上傳demo,不給個(gè)star鼓勵(lì)下我么