AVSpeechSynthesizer 在iOS 系统 将文本转化语音。在MacOS 中使用NSSpeechSynthesizer 。
AVSpeechSynthesizer * synthesizer = [[AVSpeechSynthesizer alloc] init] ;
AVSpeechUtterance * utterance = [AVSpeechUtterance speechUtteranceWithString:@"官方文档" ] ;
utterance.volume = 1.0 ; // 音量 0.0 - 1.0 之间
utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:AVSpeechSynthesisVoice.currentLanguageCode] ; // 获取当前语言的声音
utterance.rate = 0.5 ; // 说话的速度
utterance.pitchMultiplier = 0.8 ; // 发出声音的基线音调。 [0.5 - 2] 默认 = 1
[synthesizer speakUtterance:utterance] ;
AVSpeechSynthesizer 中的属性和方法
@interface AVSpeechSynthesizer : NSObject
@property(nonatomic, weak, nullable) id<AVSpeechSynthesizerDelegate> delegate;
@property(nonatomic, readonly, getter=isSpeaking) BOOL speaking;
@property(nonatomic, readonly, getter=isPaused) BOOL paused;
// 往AVSpeechSynthesizer 添加语音,将语音添加到队列中,没有播放语音的话直接播放。
- (void)speakUtterance:(AVSpeechUtterance *)utterance;
- (BOOL)stopSpeakingAtBoundary: (AVSpeechBoundary)boundary; // 停止语音
- (BOOL)pauseSpeakingAtBoundary:(AVSpeechBoundary)boundary; // 暂停语音
- (BOOL)continueSpeaking; // 继续语音播放
@property(nonatomic, retain, nullable) NSArray<AVAudioSessionChannelDescription *> *outputChannels
API_AVAILABLE(ios(10.0), watchos(3.0), tvos(10.0));
@end
AVSpeechUtterance 中的属性和方法
@interface AVSpeechUtterance : NSObject<NSCopying, NSSecureCoding>
+ (instancetype)speechUtteranceWithString:(NSString *)string; // 根据 字符串 创建
+ (instancetype)speechUtteranceWithAttributedString:(NSAttributedString *)string
API_AVAILABLE(ios(10.0), watchos(3.0), tvos(10.0));
- (instancetype)initWithString:(NSString *)string;
- (instancetype)initWithAttributedString:(NSAttributedString *)string API_AVAILABLE(ios(10.0), watchos(3.0), tvos(10.0));
@property(nonatomic, retain, nullable) AVSpeechSynthesisVoice *voice; // 播放的声音
@property(nonatomic, readonly) NSString *speechString;
@property(nonatomic, readonly) NSAttributedString *attributedSpeechString
API_AVAILABLE(ios(10.0), watchos(3.0), tvos(10.0));
@property(nonatomic) float rate; // 值固定在 AVSpeechUtteranceMinimumSpeechRate 和 AVSpeechUtteranceMaximumSpeechRate 之间。
@property(nonatomic) float pitchMultiplier; // 发出声音的基线音调。 默认为1 值在0.5 - 2 之间。
@property(nonatomic) float volume; // 音量值在 0- 1 之间。
@property(nonatomic) NSTimeInterval preUtteranceDelay; // Default is 0.0
@property(nonatomic) NSTimeInterval postUtteranceDelay; // Default is 0.0
@end
网友评论