本文只做简单的记录
1. 首先导入 AVFoundation.famework
2. 导入#import
.h 文件代码
#import
NS_ASSUME_NONNULL_BEGIN
@interfaceTKYSoundPlayer :NSObject
+ (instancetype)shareSoundPlayerInit;
//传入要播放的字符串
- (void)play:(NSString*)string;
//暂停
- (void)pausePlay;
//从头开始播放
- (void)againPlay;
@end
.m 文件
#import "TKYSoundPlayer.h"
#import
@interface TKYSoundPlayer()
{
AVSpeechSynthesizer *synth;
}
@end
staticTKYSoundPlayer*soundplayer =nil;
@implementation TKYSoundPlayer
+ (instancetype)shareSoundPlayerInit{
if(soundplayer==nil) {
soundplayer = [[TKYSoundPlayer alloc]init];
}
return soundplayer;
}
- (void)play:(NSString*)string{
if([synthisPaused]) {
//如果暂停则恢复,会从暂停的地方继续
[synth continueSpeaking];
}else{
//需要转换的文字
AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:string];
utterance.rate = 0.5; // 设置语速,范围0-1,注意0最慢,1最快;(AVSpeechUtteranceMinimumSpeechRate最慢,AVSpeechUtteranceMaximumSpeechRate最快)
synth = [[AVSpeechSynthesizer alloc] init];
synth.delegate=self;//设置代理
//获取当前系统语音
NSString*preferredLang =@"";
//设置发音,这是中文普通话
preferredLang =@"zh-CN";
AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:[NSString stringWithFormat:@"%@",preferredLang]];
utterance.voice= voice;
[synthspeakUtterance:utterance];// 开始朗读
}
}
- (void)pausePlay{
[synth pauseSpeakingAtBoundary:AVSpeechBoundaryWord];//暂停播放,调用这个方法,再开始时会从暂停的地方继续播放
}
- (void)againPlay{
[synth pauseSpeakingAtBoundary:AVSpeechBoundaryWord];//暂停播放,调用这个方法,再开始时会从暂停的地方继续播放
}
#pragma mark --- 下面是代理方法: AVSpeechSynthesizerDelegate
- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didStartSpeechUtterance:(AVSpeechUtterance*)utterance{
NSLog(@"---开始播放");
}
- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance*)utterance{
NSLog(@"---播放完成");
}
- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didPauseSpeechUtterance:(AVSpeechUtterance*)utterance{
NSLog(@"---暂停播放");
}
- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didContinueSpeechUtterance:(AVSpeechUtterance*)utterance{
NSLog(@"---继续播放");
}
- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didCancelSpeechUtterance:(AVSpeechUtterance*)utterance{
NSLog(@"---取消播放");
}