简单的使用系统功能实现语音播报功能
调用方法
//一、播放内容用中文
[[SpeechSynthesizer sharedSpeechSynthesizer] speakString:@"Leo is a handsome Boy~"];
//二、播放内容用中文
[[[SpeechSynthesizer alloc] init] speakString:@"Leo is a handsome Boy~"];
H文件
#import <UIKit/UIKit.h>
/**
* iOS7及以上版本可以使用 AVSpeechSynthesizer 合成语音
*
* 或者采用"科大讯飞"等第三方的语音合成服务
*/
@interface SpeechSynthesizer : NSObject
+ (instancetype)sharedSpeechSynthesizer;
- (BOOL)isSpeaking;
- (void)stopSpeak;
- (void)speakString:(NSString *)string;
@end
M文件
#import "SpeechSynthesizer.h"
#import <AVFoundation/AVFoundation.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;
}
//简单配置一个AVAudioSession以便可以在后台播放声音,更多细节参考AVFoundation官方文档
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDuckOthers error:NULL];
self.speechSynthesizer = [[AVSpeechSynthesizer alloc] init];
self.speechSynthesizer.delegate = self;
}
- (BOOL)isSpeaking
{
return self.speechSynthesizer.isSpeaking;
}
- (void)stopSpeak
{
if (self.speechSynthesizer)
{
[self.speechSynthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
}
}
- (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];
}
}
@end
慢慢来,一步一个巴掌印。。。。。