ios 文字转语音

搬砖的日子永远都不会结束 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值