封装相关播放文件LCAudioPlayManager,项目中导入录好的0,1,2,3,4,5,6,7,8,9,点,十百,千,万,元,user_payment(描述内容,例如“支付宝到账”),cancel_payment(“用户取消支付”)等音频文件,mp3或者wav都可以。
LCAudioPlayManager.h文件
#import
@interface LCAudioPlayManager : NSObject
+ (instancetype)sharedInstance;
// 先处理金额,得到语音文件的数组
-(NSArray *)getMusicArrayWithNum:(NSString *)numStr;
- (void)hecheng:(NSArray*)fileNameArray;
/// 系统的语音播报(红包消息)
/// AVSpeechSynthesizer(iOS10.0-12.0),之后不支持播报
- (void)speechWalllentMessage:(NSString *)numStr;
@end
LCAudioPlayManager.m文件
#import "LCAudioPlayManager.h"
#import
@implementation LCAudioPlayManager
+ (instancetype)sharedInstance{
static LCAudioPlayManager * _instance =nil;
static dispatch_once_t onceToken ;
dispatch_once(&onceToken, ^{
_instance = [[LCAudioPlayManager alloc]init] ;
}) ;
return _instance;
}
- (void)hecheng:(NSArray*)fileNameArray{
/************************合成音频并播放*****************************/
NSMutableArray*audioAssetArray = [[NSMutableArray alloc]init];
NSMutableArray*durationArray = [[NSMutableArray alloc]init];
[durationArray addObject:@(0)];
AVMutableComposition *composition = [AVMutableComposition composition];
CMTime allTime =kCMTimeZero;
for(NSInteger i =0; i < fileNameArray.count; i++) {
NSString*auidoPath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@",fileNameArray[I]] ofType:@"wav"];
AVURLAsset*audioAsset = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:auidoPath]];
[audioAsset ArrayaddObject:audioAsset];
// 音频轨道
AVMutableCompositionTrack *audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:0];
//音频素材轨道
AVAssetTrack*audioAssetTrack = [[audioAsset tracksWithMediaType:AVMediaTypeAudio]firstObject];
//音频合并-插入音轨文件
[audioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset.duration) ofTrack:audioAssetTrack atTime:allTime error:nil];
//更新当前的位置
allTime =CMTimeAdd(allTime, audioAsset.duration);
}
//合并后的文件导出- `presetName`要和之后的`session.outputFileType`相对应。
AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetAppleM4A];
NSString *outPutFilePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"test.m4a"];
if([[NSFileManager defaultManager]fileExistsAtPath:outPutFilePath]) {
[[NSFileManager defaultManager] removeItemAtPath:outPutFilePath error:nil];
}
//查看当前session支持的fileType类型
NSLog(@"---%@",[session supportedFileTypes]);
session.outputURL= [NSURL fileURLWithPath:outPutFilePath];
session.outputFileType = AVFileTypeAppleM4A; //与上述的`present`相对应
session.shouldOptimizeForNetworkUse = YES; //优化网络
[session exportAsynchronouslyWithCompletionHandler:^{
NSLog(@"+++%@",[NSThread currentThread]);
if (session.status == AVAssetExportSessionStatusCompleted) {
NSLog(@"合并成功----%@", outPutFilePath);
NSURL*url = [NSURL fileURLWithPath:outPutFilePath];
static SystemSoundIDsoundID =0;
AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(url), &soundID);
AudioServicesPlayAlertSoundWithCompletion(soundID, ^{
NSLog(@"播放完成");
AudioServicesDisposeSystemSoundID(soundID);
});
}else{
//其他情况,具体请看这里`AVAssetExportSessionStatus`.
}
}];
}
-(NSArray *)getMusicArrayWithNum:(NSString *)numStr
{
NSString*finalStr = [self caculateNumber:numStr];
//前部分字段例如:***到账 user_payment是项目自定义的音乐文件
NSMutableArray *finalArr = [[NSMutableArray alloc] initWithObjects:@"user_payment", nil];
for(int i=0; i
[finalArr addObject:[finalStr substringWithRange:NSMakeRange(i,1)]];
}
return finalArr;
}
-(NSString*)caculateNumber:(NSString*)numstr {
NSArray *numberchar = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"];
NSArray*inunitchar =@[@"",@"十",@"百",@"千"];
NSArray*unitname =@[@"",@"万",@"亿"];
NSString*valstr =[NSString stringWithFormat:@"%.2f",numstr.doubleValue] ;
NSString*prefix =@"";
// 将金额分为整数部分和小数部分
NSString*head = [valstr substringToIndex:valstr.length-2-1] ;
NSString*foot = [valstr substringFromIndex:valstr.length-2] ;
//处理整数部分
if([head isEqualToString:@"0"]) {
prefix =@"0";
}else{
NSMutableArray *ch = [[NSMutableArray alloc]init] ;
for(int i =0; i < head.length; i++) {
NSString* str = [NSString stringWithFormat:@"%x",[head characterAtIndex:i]-'0'] ;
[ch addObject:str] ;
}
int zeronum =0;
for(int i =0; i < ch.count; i++) {
NSInteger index = (ch.count-1- i)%4; //取段内位置
NSInteger indexloc = (ch.count-1- i)/4; //取段位置
if ([[ch objectAtIndex:i] isEqualToString:@"0"]) {
zeronum ++ ;
}else{
if(zeronum !=0) {
if(index !=3) {
prefix=[prefix stringByAppendingString:@"零"];
}
zeronum =0;
}
if(ch.count>i) {
NSInteger numIndex = [[ch objectAtIndex:i] intValue];
if(numberchar.count>numIndex) {
prefix = [prefix stringByAppendingString:[numberchar objectAtIndex:numIndex]] ;
}
}
if(inunitchar.count>index) {
prefix = [prefix stringByAppendingString:[inunitchar objectAtIndex:index]] ;
}
}
if(index ==0&& zeronum <4) {
if(unitname.count>indexloc) {
prefix = [prefix stringByAppendingString:[unitname objectAtIndex:indexloc]] ;
}
}
}
}
//1十开头的改为十
if([prefix hasPrefix:@"1十"]) {
prefix = [prefix stringByReplacingOccurrencesOfString:@"1十" withString:@"十"] ;
}
//处理小数部分
if([foot isEqualToString:@"00"]) {
prefix = [prefix stringByAppendingString:@"元"] ;
}else{
prefix = [prefix stringByAppendingString:[NSString stringWithFormat:@"点%@元", foot]] ;
}
return prefix ;
}
#pragma mark iOS12.1以下 播放语音
//语音播报红包消息
- (void)speechWalllentMessage:(NSString *)numStr {
//播放语音
// 合成器 控制播放,暂停
AVSpeechSynthesizer*_synthesizer;
// 实例化说话的语言,说中文、英文
AVSpeechSynthesisVoice *_voice;
_voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-TW"];//zh_CN
// 要朗诵,需要一个语音合成器
_synthesizer = [[AVSpeechSynthesizer alloc]init];
AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:[NSString stringWithFormat:@"%@",numStr]];
//指定语音,和朗诵速度
utterance.voice= _voice;
utterance.rate=0.53;//0.6//越大语速越快
utterance.pitchMultiplier = 1.2f; //改变音调//1.0f 0.5-2,1一下男声,以上女生
utterance.volume=1;
//启动
[_synthesizer speakUtterance:utterance];
}
@end
在需要播报的地方调用#import "LCAudioPlayManager.h"
NSArray *musicArr = [[LCAudioPlayManager sharedInstance] getMusicArrayWithNum:amountStr];
//amountStr是金额例:100 其他封装文件做了相应处理
[[LCAudioPlayManagersharedInstance]hecheng:musicArr];
//系统自带语音合成调用
[[LCAudioPlayManager sharedInstance] speechWalllentMessage:contentStr];
//contentStr需要播报的文字内容,例:“支付宝到账100.01元”