使用 AVAudioRecorder 前,要先引入 AVFoundation。錄音檔通常會存到 Documents 目錄,因此可先取得 Documents 路徑,再組出完整檔案路徑。
NSString *destinationString = [[self documentsPath] stringByAppendingPathComponent:filenameField.text];
NSURL *destinationURL = [NSURL fileURLWithPath:destinationString];
NSError *recorderSetupError = nil;
AVAudioRecorder *audioRecorder = [[AVAudioRecorder alloc] initWithURL:destinationURL settings:recordSettings error:NULL];
settings 是包含鍵值對的 NSDictionary。線性 PCM 常見設定包括:
建立 AVAudioRecorder 後,錄音流程就很直接:
[audioRecorder record];
[audioRecorder pause];
[audioRecorder stop];
實務上也要處理錄音權限、儲存路徑與檔案名稱衝突等問題,才能做出穩定的錄音功能。