音频录制
- 引入框架:引入
AVFoundation
框架,该框架提供了丰富的音频处理功能。
- 关键类:
AVAudioSession
:用于配置音频会话,设置音频录制的模式、类别等。例如,设置为录制模式:
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *sessionError;
[audioSession setCategory:AVAudioSessionCategoryRecord error:&sessionError];
- `AVAudioRecorder`:负责音频的实际录制操作。初始化`AVAudioRecorder`时,需要指定音频文件的URL以及录制设置。
NSURL *recordedAudioURL = [NSURL fileURLWithPath:filePath];
NSDictionary *recordSettings = @{
AVFormatIDKey: @(kAudioFormatMPEG4AAC),
AVSampleRateKey: @44100.0,
AVNumberOfChannelsKey: @2,
AVEncoderAudioQualityKey: @(AVAudioQualityHigh)
};
NSError *recorderError;
AVAudioRecorder *audioRecorder = [[AVAudioRecorder alloc] initWithURL:recordedAudioURL settings:recordSettings error:&recorderError];
if (audioRecorder) {
[audioRecorder prepareToRecord];
[audioRecorder record];
}
- 音频格式细节:在录制设置中,通过
AVFormatIDKey
指定音频格式,如kAudioFormatMPEG4AAC
表示AAC格式。AVSampleRateKey
设置采样率,常见的有44100Hz。AVNumberOfChannelsKey
确定声道数,立体声通常为2。AVEncoderAudioQualityKey
设置音频编码质量。
音频播放
- 引入框架:同样是
AVFoundation
框架。
- 关键类:
AVAudioPlayer
:用于音频的播放。初始化时需要指定音频文件的URL。
NSURL *audioFileURL = [NSURL fileURLWithPath:filePath];
NSError *playerError;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileURL error:&playerError];
if (audioPlayer) {
[audioPlayer prepareToPlay];
[audioPlayer play];
}
- 音频格式细节:
AVAudioPlayer
支持多种常见音频格式,如MP3、AAC等。在初始化时,只要音频文件格式在支持范围内,AVAudioPlayer
能够自动处理格式解析并播放。如果音频格式不支持,initWithContentsOfURL:error:
方法会返回nil
并在error
中给出相关信息。