iOS音频开发(录音+播放+剪辑+合成+压缩转码)

iOS音频开发(录音+播放+剪辑+合成+压缩转码)

From: http://blog.csdn.net/feng2qing/article/details/67655175

录音:

AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *sessionError;

[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
[session setActive:YES error:nil];

NSDictionary *setting = [NSDictionary dictionaryWithObjectsAndKeys:
                               [NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,
                               [NSNumber numberWithFloat:8000], AVSampleRateKey, 
                               [NSNumber numberWithInt:2], AVNumberOfChannelsKey, 
                               [NSNumber numberWithInt:16], AVLinearPCMBitDepthKey,  
                               [NSNumber numberWithBool:NO], AVLinearPCMIsNonInterleaved,  
                               [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,  
                               [NSNumber numberWithBool:NO], AVLinearPCMIsBigEndianKey,  
                               [NSNumber numberWithInt:AVAudioQualityMax], AVEncoderAudioQualityKey,  
                               nil];
self.audioRecorder.delegate = self;

self.audioRecorder.meteringEnabled = YES;

self.audioRecorder = [[AVAudioRecorder alloc] initWithURL:[NSURL URLWithString:filePath] settings:setting error:nil];

[self.audioRecorder prepareToRecord];
[self.audioRecorder record];


[self.audioRecorder pause];

[self.audioRecorder stop];




- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag;

- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError * __nullable)error;

- (void)audioRecorderBeginInterruption:(AVAudioRecorder *)recorder NS_DEPRECATED_IOS(2_2, 8_0);

- (void)audioRecorderEndInterruption:(AVAudioRecorder *)recorder withOptions:(NSUInteger)flags NS_DEPRECATED_IOS(6_0, 8_0);

播放

AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *sessionError;
[session setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
[session setActive:YES error:nil];


[[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sensorStateChange:)name:UIDeviceProximityStateDidChangeNotification object:nil];

self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:filePath] error:nil];

self.audioPlayer.delegate = self;

[self.audioPlayer prepareToPlay];
[self.audioPlayer play];


[self.audioPlayer stop];

[self.audioPlayer pause];


if ([[UIDevice currentDevice] proximityState] == YES) {

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
} else {

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
}



- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag;

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error;

- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player NS_DEPRECATED_IOS(2_2, 8_0);

- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags NS_DEPRECATED_IOS(6_0, 8_0);

剪辑

//AVURLAsset是AVAsset的子类,AVAsset类专门用于获取多媒体的相关信息,包括获取多媒体的画面、声音等信息.而AVURLAsset子类的作用则是根据NSURL来初始化AVAsset对象.
AVURLAsset *videoAsset = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:filePath]];
//音频输出会话
//AVAssetExportPresetAppleM4A: This export option will produce an audio-only .m4a file with appropriate iTunes gapless playback data(输出音频,并且是.m4a格式)
AVAssetExportSession *exportSession = [AVAssetExportSession exportSessionWithAsset:videoAsset presetName:AVAssetExportPresetAppleM4A];
//设置输出路径 / 文件类型 / 截取时间段
exportSession.outputURL = [NSURL fileURLWithPath:resultPath];
exportSession.outputFileType = AVFileTypeAppleM4A;
exportSession.timeRange = CMTimeRangeFromTimeToTime(CMTimeMake(time1, 1), CMTimeMake(time2, 1));
[exportSession exportAsynchronouslyWithCompletionHandler:^{
    //exporeSession.status
}];

合成

将路径filePath1和路径filePath2下的音频合成

AVURLAsset *videoAsset1 = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:filePath1] options:nil];
AVURLAsset *videoAsset2 = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:filePath2] options:nil];

AVAssetTrack *assetTrack1 = [[videoAsset1 tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
AVAssetTrack *assetTrack2 = [[videoAsset2 tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];

AVMutableComposition *composition = [AVMutableComposition composition];
AVMutableCompositionTrack *compositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];

[compositionTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset1.duration) ofTrack:assetTrack1 atTime:kCMTimeZero error:nil];
[compositionTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset2.duration) ofTrack:assetTrack2 atTime:videoAsset1.duration error:nil];

AVAssetExportSession *exporeSession = [AVAssetExportSession exportSessionWithAsset:composition presetName:AVAssetExportPresetAppleM4A];
exporeSession.outputFileType = AVFileTypeAppleM4A;
exporeSession.outputURL = [NSURL fileURLWithPath:resultPath];
[exporeSession exportAsynchronouslyWithCompletionHandler:^{

}];

压缩转码

下载LAME (Lame Aint an MP3 Encoder)

双击解压后放到一个文件夹下,文件夹需要命名为lame,否则无法生成.h.a文件

使用Terminal进入该文件夹,编译生成静态库,[脚本代码][3]

[3]: https://github.com/kewlbear/lame-ios-build/blob/master/build-lame.sh
1
2
3
4
5
6
7
$:cd cd /Users/mac/Desktop/lame
//创建build_lame.sh
$:touch build_lame.sh
//打开build_lame.sh,粘贴脚本代码
$:open build_lame.sh
//编译执行脚本,生成静态库,需要输入本机密码
$:sudo sh build_lame.sh

这里写图片描述

fat-lame文件夹下的include文件夹和lib文件夹放入工程,再写一个OC的类调用lame.h

@try {
    int read, write;
    FILE *pcm = fopen([filePath cStringUsingEncoding:1], "rb");
    fseek(pcm, 4*1024, SEEK_CUR);
    FILE *mp3 = fopen([resultPath cStringUsingEncoding:1], "wb");

    const int PCM_SIZE = 8192;
    const int MP3_SIZE = 8192;
    short int pcm_buffer[PCM_SIZE*2];
    unsigned char mp3_buffer[MP3_SIZE];


    lame_t lame = lame_init();

    lame_set_in_samplerate(lame, 8000);
    lame_set_num_channels(lame,2);
    lame_set_out_samplerate(lame, 8000);
    lame_set_brate(lame, 8);

    lame_set_quality(lame, 7);


    lame_set_VBR(lame, vbr_default);
    lame_init_params(lame);

    do {
        size_t size = (size_t)(2 * sizeof(short int));
        read = fread(pcm_buffer, size, PCM_SIZE, pcm);
        if (read == 0) {
            write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
        } else {
            write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
        }
        fwrite(mp3_buffer, write, 1, mp3);

    } while (read != 0);

    lame_close(lame);
    fclose(mp3);
    fclose(pcm);
}
@catch (NSException *exception) {
    NSLog(@"%@",[exception description]);
}
@finally {

    return resultPath;
}

基本上可以将100K左右的录音文件压缩到10K以下

参考1 参考2 参考3 参考4

Author

陈昭

Posted on

2017-05-25

Updated on

2021-12-27

Licensed under

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

Kommentare

You forgot to set the shortname for Disqus. Please set it in _config.yml.