一、说明
最近项目中用到播放文字语音功能,经过搜索总结,做了一个简单封装,实现调用一句话播放制定文字功能。
下载地址:GitHub
调用如下:
[self playNotifySound:@"播放此文字"];
二、
1、demo中包含两个文件
SDSoundPlayer.h
SDSoundPlayer.m
SDSoundPlayer.h 中首先需要倒入基础框架
#import <AVFoundation/AVFoundation.h>
然后定义属性及方法
@property(nonatomic,assign)float rate; //语速
@property(nonatomic,assign)float volume; //音量
@property(nonatomic,assign)float pitchMultiplier; //音调
@property(nonatomic,assign)BOOL autoPlay; //自动播放
//实例对象
+(SDSoundPlayer *)SDSoundPlayerInit;
//基础属性设置
-(void)setDefaultWithVolume:(float)aVolume rate:(CGFloat)aRate pitchMultiplier:(CGFloat)aPitchMultiplier;
//播放文字
-(void)play:(NSString *)string;
SDSoundPlayer.m 中实现播放声音的方法,语速、音量、语言、语调都可以行修改 ,这里只说一下播放声音的方法,其他方法请自行下载demo查看 ****zh-CN是中文普通话****
//播放声音
-(void)play:(NSString *)string{
if(string && string.length > 0){
AVSpeechSynthesizer *player = [[AVSpeechSynthesizer alloc]init];
AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc]initWithString:string];//语音内容
utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];//语言
utterance.rate = self.rate; //语速
utterance.volume = self.volume; //音量(0.0~1.0)默认为1.0
utterance.pitchMultiplier = self.pitchMultiplier; //语调 (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];
}
调用
[self playNotifySound:message];
目前找到的只有这个方法是稍微简单的,但是听起来声音不太好听