音频的录制与播放

首先导入AVFoundation库

#import 

定义全局的recorder、player和audiosession

@property (nonatomic, strong) AVAudioRecorder *audioRecorder;
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@property (nonatomic, strong) AVAudioSession *audioSession;

开始录音

NSString *directory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)[0];
NSString *filePath = [directory stringByAppendingPathComponent:@"voice.caf"];
NSURL *url = [NSURL URLWithString:filePath];
    
NSDictionary *settings = @{AVEncoderAudioQualityKey : @(AVAudioQualityMin),
                               AVEncoderBitRateKey : @16,
                               AVNumberOfChannelsKey : @2, AVSampleRateKey : @44100.0};
    
 AVAudioSession *audioSession = [AVAudioSession sharedInstance];

[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error:nil];
    
    _audioRecorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:nil];
    _audioRecorder.delegate = self;
    if (![_audioRecorder isRecording]) {
        [_audioRecorder prepareToRecord];
        [_audioRecorder record];
    }

结束录音

 if ([_audioRecorder isRecording]) {
        [_audioRecorder stop];
    }

播放

_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    _audioPlayer.volume = 1;
    if (_audioPlayer) {
        [_audioPlayer prepareToPlay];
        [_audioPlayer play];
    }

获取录音长度

NSString *directory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)[0];
    NSString *filePath = [directory stringByAppendingPathComponent:@"voice.caf"];
    NSURL *url = [NSURL fileURLWithPath:filePath];
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
    CMTime duration = asset.duration;
    NSUInteger audioDurationSeconds = CMTimeGetSeconds(duration);

这边需要注意,url获取要通过fileURLWithPath

你可能感兴趣的:(音频的录制与播放)