您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 錄音功能實作:AVAudioRecorder 入門

編輯:iOS 開發綜合

在 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];
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved