搬砖的日子永远都不会结束 Because—>生活不止眼前的苟且,还有未来的苟且。
@interface TKYSoundPlayer : NSObject
+ (instancetype)shareSoundPlayerInit;
//传入要播放的字符串
- (void)play:(NSString*)string;
//暂停
- (void)pausePlay;
//从头开始播放
- (void)againPlay;
@end
#import "TKYSoundPlayer.h"
#import <AVFoundation/AVFoundation.h>
@interface TKYSoundPlayer()<AVSpeechSynthesizerDelegate>{
AVSpeechSynthesizer *synth;
}
@end
static TKYSoundPlayer*soundplayer =nil;
@implementation TKYSoundPlayer
+ (instancetype)shareSoundPlayerInit{
if(soundplayer==nil) {
soundplayer = [[TKYSoundPlayer alloc]init];
}
return soundplayer;
}
- (void)play:(NSString*)string{
if([synth isPaused]) {
//如果暂停则恢复,会从暂停的地方继续
[synth continueSpeaking];
}else{
//需要转换的文字
AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:string];
// utterance.rate = 0.1;
// 设置语速,范围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;
[synth speakUtterance: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(@"---取消播放");
}
@end