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

iOS 錄音實作:AVAudioRecorder 完整用法

編輯:iOS 開發綜合

在 AVFoundation 框架中,AVAudioRecorder 專門負責錄音,支援多種音訊格式。本文先整理常用 API,再給出一個可直接運行的完整範例。

一、常用屬性

  • recording(唯讀):是否正在錄音。
  • url(唯讀):錄音檔案位址。
  • settings(唯讀):目前的錄音設定。
  • currentTime(唯讀):目前錄音時長,僅在錄音狀態下有效。
  • deviceCurrentTime(唯讀):裝置時間長度,任何時候都可存取。
  • meteringEnabled:是否啟用音量測量,啟用後才能取得分貝資料。
  • channelAssignments:目前錄音使用的通道。

二、常用方法

  • initWithURL:settings:error::初始化錄音機。注意 url 必須是本地檔案位址,settings 描述格式與編碼。
  • prepareToRecord:準備錄音,主要用於建立緩衝區。若不手動呼叫,record 也會自動觸發。
  • record:開始錄音。
  • recordAtTime::在指定時間開始錄音,常用於暫停後恢復。
  • recordForDuration::依指定時長錄音。
  • recordAtTime:forDuration::指定起始時間與時長。
  • pause/stop:暫停/停止。
  • deleteRecording:刪除錄音,前提是錄音機必須處於停止狀態。
  • updateMeters:更新測量資料,需 meteringEnabled 為 YES。
  • peakPowerForChannel:/averagePowerForChannel::指定通道的峰值與平均值,呼叫 updateMeters 後才有值。

三、delegate 方法

  • audioRecorderDidFinishRecording:successfully::錄音完成。
  • audioRecorderEncodeErrorDidOccur:error::編碼發生錯誤。

四、錄音設定

建立錄音機時除了指定路徑,還必須提供錄音設定,因為錄音機需要知道格式、取樣率、通道數與每個取樣點的位元數。一般只需要幾個常用鍵值,詳見官方文件中的 “AV Foundation Audio Settings Constants”。

五、完整範例

以下實作包含錄音、暫停、繼續、取消、停止與播放。

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

#define kAudioFileName @"test.caf"

@interface ViewController () <AVAudioRecorderDelegate>
@property (nonatomic, strong) AVAudioRecorder *audioRecorder;  // 錄音機
@property (nonatomic, strong) AVAudioPlayer   *audioPlayer;    // 播放器
@property (nonatomic, strong) NSTimer         *timer;          // 音量監控
@property (weak, nonatomic) IBOutlet UIProgressView *audioPower;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setAudioSession];
}

#pragma mark - 音訊工作階段

- (void)setAudioSession {
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    // 設為播放 + 錄音,錄完才能立即回放
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [audioSession setActive:YES error:nil];
}

#pragma mark - 錄音設定

- (NSDictionary *)getAudioSetting {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];      // 格式
    [dic setObject:@(8000)             forKey:AVSampleRateKey];         // 取樣率
    [dic setObject:@(1)                forKey:AVNumberOfChannelsKey];   // 單聲道
    [dic setObject:@(8)                forKey:AVLinearPCMBitDepthKey];  // 8/16/24/32
    [dic setObject:@(YES)              forKey:AVLinearPCMIsFloatKey];   // 浮點取樣
    return dic;
}

#pragma mark - 檔案路徑

- (NSURL *)getSavePath {
    NSString *url = [NSSearchPathForDirectoriesInDomains(
        NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    url = [url stringByAppendingPathComponent:kAudioFileName];
    return [NSURL fileURLWithPath:url];
}

#pragma mark - 懶載入

- (NSTimer *)timer {
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                  target:self
                                                selector:@selector(audioPowerChange)
                                                userInfo:nil
                                                 repeats:YES];
    }
    return _timer;
}

- (AVAudioRecorder *)audioRecorder {
    if (!_audioRecorder) {
        NSError *error = nil;
        _audioRecorder = [[AVAudioRecorder alloc]
            initWithURL:[self getSavePath]
               settings:[self getAudioSetting]
                  error:&error];
        if (error) {
            NSLog(@"建立錄音機失敗:%@", error.localizedDescription);
            return nil;
        }
        _audioRecorder.delegate = self;
        _audioRecorder.meteringEnabled = YES;
    }
    return _audioRecorder;
}

- (AVAudioPlayer *)audioPlayer {
    if (!_audioPlayer) {
        NSError *error = nil;
        _audioPlayer = [[AVAudioPlayer alloc]
            initWithContentsOfURL:[self getSavePath] error:&error];
        if (error) {
            NSLog(@"建立播放器失敗:%@", error.localizedDescription);
            return nil;
        }
    }
    return _audioPlayer;
}

#pragma mark - AVAudioRecorderDelegate

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder
                            successfully:(BOOL)flag {
    if (![self.audioPlayer isPlaying]) {
        [self.audioPlayer play];
    }
}

- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder
                                   error:(NSError *)error {
    NSLog(@"錄音編碼錯誤:%@", error.localizedDescription);
}

#pragma mark - 音量監控

- (void)audioPowerChange {
    [self.audioRecorder updateMeters];   // 必須先更新
    float power = [self.audioRecorder averagePowerForChannel:0];
    // 音量範圍為 -160 ~ 0
    self.audioPower.progress = (1.0 / 160) * (power + 160);
}

#pragma mark - 操作

- (IBAction)startRecord:(id)sender {
    if (![self.audioRecorder isRecording]) {
        [self.audioRecorder record];
        self.timer.fireDate = [NSDate distantPast];   // 啟動監控
    }
}

- (IBAction)pause:(id)sender {
    if ([self.audioRecorder isRecording]) {
        [self.audioRecorder pause];
        self.timer.fireDate = [NSDate distantFuture]; // 暫停監控
    }
}

// 恢復錄音只需再次呼叫 record,
// AVAudioSession 會記住上次位置並向後追加
- (IBAction)goon:(id)sender {
    [self startRecord:nil];
}

- (IBAction)stop:(id)sender {
    if ([self.audioRecorder isRecording]) {
        [self.audioRecorder stop];
        self.timer.fireDate = [NSDate distantFuture];
    }
}

- (IBAction)cancelRecord:(id)sender {
    self.audioRecorder.delegate = nil;
    if ([self.audioRecorder isRecording]) {
        [self.audioRecorder stop];
    }
    self.audioRecorder = nil;   // 連同檔案設定一起丟棄
}

- (IBAction)play:(id)sender {
    if (![self.audioPlayer isPlaying]) {
        [self.audioPlayer play];
    }
}

@end

幾個實務提醒

  • getSavePath 中原本用 NSURL URLWithString: 處理檔案路徑是錯的,本地檔案必須用 fileURLWithPath:,否則錄音會靜默失敗。
  • 取音量時通道索引從 0 開始,範例中原先寫成 1 會取不到資料。
  • 正式環境建議改用 AVAudioRecorder 的 recordAtTime:forDuration: 做時長控制,並在 stop 後呼叫 deleteRecording 的時機上做清楚規劃。
  • 錄音涉及隱私,記得在 Info.plist 中補上 NSMicrophoneUsageDescription 說明用途。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved