AVFundation之语音合成-AVSpeechSynthesizer

在IOS开发中,我们很多时候要用到将文字内容转换为语音播放的需求,这个需求除了使用第三方开发的解决方案(例如科大讯飞,这个貌似很有名的)外,对于简单的语音播放我们完全可以自己实现.

使用很简单,直接上代码:

AVFundation之语音合成-AVSpeechSynthesizer_第1张图片
控制界面
#import "ViewController.h"

/*!---------添加AVFoundation库----------!*/
#import 

 @interface ViewController ()

//属性声明
@property(nonatomic,strong)AVSpeechSynthesizer * synthesizer;
@property(nonatomic,strong)AVSpeechUtterance * utterance;
@property(nonatomic,getter=isPlaying)BOOL playing;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

self.playing = NO;

/*!---------1.synthesizer(合成器)的初始化----------!*/
self.synthesizer = [[AVSpeechSynthesizer alloc]init];
//    delegate中有synthesizer各种状态的回调方法
//    self.synthesizer.delegate = self;


/*!---------2.utterance(内容信息)的初始化----------!*/
self.utterance = [[AVSpeechUtterance alloc]initWithString:@" start with English,在IOS开发中,我们很多时候要用到将文字内容转换为语音播放的需求,这个需求除了使用第三方开发的解决方案外,对于简单的语音播放我们完全可以自己实现"];

//设置语言@"zh-CN"中文播放,@"en-US"英文播放等,其它语音,可以百度
self.utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
//播放速率
self.utterance.rate = 0.5;
//音高[0.5-2]默认1
self.utterance.pitchMultiplier = 1;
//播放音量[0-1]默认1;
self.utterance.volume = 1;
}


//开始
- (IBAction)start:(id)sender {

//如果是暂停状态,则继续播放,否则重头播放
if ([self.synthesizer isPaused]) {
    [self.synthesizer continueSpeaking];
}
else{
    if (!self.playing) {
         //如果正在播放,在调用speakUtterance方法会crash
        [self.synthesizer speakUtterance:self.utterance];
        self.playing = !self.playing;
    }
}
}

//停止
- (IBAction)stop:(id)sender {
/**
 *  参数 boundary
 *  AVSpeechBoundaryImmediate:立即停止
 *  AVSpeechBoundaryWord:播放完当前的单词在停止
 */
[self.synthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
self.playing = NO;
}


//暂停
- (IBAction)pause:(id)sender {
[self.synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryWord];
}

@end

你可能感兴趣的:(AVFundation之语音合成-AVSpeechSynthesizer)