Files
yingmeng-ios-switf/yinmeng-ios/Base/Security/RecordVoiceManager.m
2024-03-05 14:04:09 +08:00

77 lines
2.9 KiB
Objective-C

//
// RecordVoiceManager.m
// yinmeng-ios
//
// Created by yinmeng on 2024/3/1.
//
#import "RecordVoiceManager.h"
@implementation RecordVoiceManager
-(void)stopRecord{
[self.recorder stop];
self.recorder = nil;
}
/// 初始化录音对象
- (void)initWithRecord {
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
//录音设置
NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] init];
[recordSettings setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey: AVFormatIDKey];
[recordSettings setValue :[NSNumber numberWithFloat:16000.0] forKey: AVSampleRateKey];
[recordSettings setValue :[NSNumber numberWithInt:2] forKey: AVNumberOfChannelsKey];
[recordSettings setValue :[NSNumber numberWithInt:16] forKey: AVLinearPCMBitDepthKey];
[recordSettings setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];
NSError *error = nil;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *date = [dateFormat stringFromDate:[NSDate date]];
self.file = [NSString stringWithFormat:@"voiceShow_%@.wav", date];
NSFileManager *fileMgr = [[NSFileManager alloc] init];
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"voiceShow"];
self.path = [filePath stringByAppendingPathComponent:self.file];
if (![fileMgr fileExistsAtPath:filePath]) {
[fileMgr createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
}
if (![fileMgr fileExistsAtPath:filePath]) { return; }
NSURL *fileUrl = [NSURL fileURLWithPath:self.path];
self.recorder = [[AVAudioRecorder alloc] initWithURL:fileUrl settings:recordSettings error:&error];
self.recorder.meteringEnabled = YES;
[self.recorder updateMeters];
NSLog(@"%f",[self.recorder peakPowerForChannel:0]);
if(!self.recorder) {
return;
}
if(![self.recorder prepareToRecord]) {
return;
}
BOOL status = [self.recorder record];
NSLog(@"%d",status);
}
- (void)playFilePathVoice {
if (self.isPlayVoice) {
[self.player stop];
self.player = nil;
self.isPlayVoice = NO;
return;
}
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionAllowBluetooth error:nil];
BOOL isFile = [[NSFileManager defaultManager] fileExistsAtPath:self.path];
NSError *AVerror = NULL;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:self.path] error:&AVerror];
self.player.volume = 1;
self.player.numberOfLoops = -1;
[self.player prepareToPlay];
[self.player play];
self.isPlayVoice = YES;
}
@end