一、說明
最近項目中用到播放文字語音功能,經(jīng)過搜索總結(jié),做了一個簡單封裝,實現(xiàn)調(diào)用一句話播放制定文字功能。
下載地址:GitHub
調(diào)用如下:
[self playNotifySound:@"播放此文字"];
二、
1、demo中包含兩個文件
SDSoundPlayer.h
SDSoundPlayer.m
SDSoundPlayer.h 中首先需要倒入基礎(chǔ)框架
#import <AVFoundation/AVFoundation.h>
然后定義屬性及方法
@property(nonatomic,assign)float rate; //語速
@property(nonatomic,assign)float volume; //音量
@property(nonatomic,assign)float pitchMultiplier; //音調(diào)
@property(nonatomic,assign)BOOL autoPlay; //自動播放
//實例對象
+(SDSoundPlayer *)SDSoundPlayerInit;
//基礎(chǔ)屬性設(shè)置
-(void)setDefaultWithVolume:(float)aVolume rate:(CGFloat)aRate pitchMultiplier:(CGFloat)aPitchMultiplier;
//播放文字
-(void)play:(NSString *)string;
SDSoundPlayer.m 中實現(xiàn)播放聲音的方法,語速、音量、語言、語調(diào)都可以行修改 ,這里只說一下播放聲音的方法,其他方法請自行下載demo查看 ****zh-CN是中文普通話****
//播放聲音
-(void)play:(NSString *)string{
if(string && string.length > 0){
AVSpeechSynthesizer *player = [[AVSpeechSynthesizer alloc]init];
AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc]initWithString:string];//語音內(nèi)容
utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];//語言
utterance.rate = self.rate; //語速
utterance.volume = self.volume; //音量(0.0~1.0)默認為1.0
utterance.pitchMultiplier = self.pitchMultiplier; //語調(diào) (0.5-2.0)
utterance.postUtteranceDelay = 1;
[player speakUtterance:utterance];
}
}
三、具體使用
在要使用的地方導入
#import "SDSoundPlayer.h"
寫一個方法,其中message即為要播放的文字
- (void)playNotifySound:(NSString *)message {
SDSoundPlayer *player = [SDSoundPlayer SDSoundPlayerInit];
[player setDefaultWithVolume:-1.0 rate:0.5 pitchMultiplier:-1.0];
[player play:message];
}
調(diào)用
[self playNotifySound:message];
目前找到的只有這個方法是稍微簡單的,但是聽起來聲音不太好聽