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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章