在 iOS 中,錄音通常會使用 AVFoundation 裡的 AVAudioRecorder。它適合錄製語音、備忘或短影音素材。
先匯入 AVFoundation,宣告一個全域的 AVAudioRecorder 物件,並在按鈕事件中切換錄音與停止。
錄音檔可存到 CachesDirectory,檔名可用時間戳產生。初始化時需設定聲道數、取樣率、位元深度、編碼品質與位元率。
NSString *name = [NSString stringWithFormat:@"%d.aiff", (int)[NSDate date].timeIntervalSince1970];
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:name];
NSDictionary *settings = @{
AVNumberOfChannelsKey: @2,
AVSampleRateKey: @44100,
AVLinearPCMBitDepthKey: @32,
AVEncoderAudioQualityKey: @(AVAudioQualityMax),
AVEncoderBitRateKey: @128000
};
audioRecorder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:path]
settings:settings
error:&error];
[audioRecorder prepareToRecord];
[audioRecorder record];
錄音結束後,可透過 NSFileManager 搜尋 Caches 目錄中的 aiff 檔,做為後續播放或上傳用途。
NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachesPath];
NSMutableArray *audioFiles = [NSMutableArray array];
for (NSString *file in files) {
if ([[file pathExtension] isEqualToString:@"aiff"]) {
[audioFiles addObject:file];
}
}