// // AudioRecorderManager.m // 双子星云手机 // // Created by xd h on 2025/3/28. // #import "AudioRecorderManager.h" @implementation AudioRecorderManager + (instancetype)sharedManager { static AudioRecorderManager *sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[self alloc] init]; }); return sharedInstance; } - (instancetype)init { self = [super init]; if (self) { [self setupAudioSession]; } return self; } - (void)setupAudioSession { AVAudioSession *audioSession = [AVAudioSession sharedInstance]; NSError *error = nil; [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&error]; [audioSession setActive:YES error:&error]; if (error) { NSLog(@"Audio Session error: %@", error.localizedDescription); } } - (void)startRecording { if ([self isRecording]) { [self stopRecording]; return; } // 设置录音文件路径 NSString *documentsPath = kSHPath_Record; self.recordedFilePath = [documentsPath stringByAppendingPathComponent:@"recording.m4a"]; NSURL *outputFileURL = [NSURL fileURLWithPath:self.recordedFilePath]; // 录音设置 NSDictionary *recordSettings = @{ AVFormatIDKey: @(kAudioFormatMPEG4AAC), AVSampleRateKey: @44100.0, AVNumberOfChannelsKey: @2, AVEncoderAudioQualityKey: @(AVAudioQualityHigh) }; NSError *error = nil; self.audioRecorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSettings error:&error]; self.audioRecorder.delegate = self; if (error) { NSLog(@"Audio Recorder error: %@", error.localizedDescription); } else { [self.audioRecorder prepareToRecord]; [self.audioRecorder record]; NSLog(@"Recording started"); } } - (void)stopRecording { if ([self isRecording]) { [self.audioRecorder stop]; self.audioRecorder = nil; NSLog(@"Recording stopped"); } } - (void)playRecording { if ([self isPlaying]) { [self stopPlaying]; return; } if (!self.recordedFilePath) { NSLog(@"No recording to play"); return; } NSError *error = nil; self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:self.recordedFilePath] error:&error]; self.audioPlayer.numberOfLoops = 0; if (error) { NSLog(@"Audio Player error: %@", error.localizedDescription); } else { [self.audioPlayer play]; NSLog(@"Playing recording"); } } - (void)stopPlaying { if ([self isPlaying]) { [self.audioPlayer stop]; self.audioPlayer = nil; NSLog(@"Playback stopped"); } } - (BOOL)isRecording { return self.audioRecorder && self.audioRecorder.isRecording; } - (BOOL)isPlaying { return self.audioPlayer && self.audioPlayer.isPlaying; } #pragma mark - AVAudioRecorderDelegate - (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag { if (flag) { NSLog(@"Recording finished successfully"); } else { NSLog(@"Recording failed"); } self.audioRecorder = nil; } @end