iOS 录音的暂停与试听 Bug

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xjh093/article/details/85163304

需求

在录音过程中,可以暂停、继续、试听。
以为很简单,只要调用系统的方法就行。
结果却…


实际

录音暂停的时候,播放录音文件是没有声音的。
只能在停止之后,播放录音文件才有声音。


办法

录制多个音频,最后把音频合成一个。

+ (void)mergeAudios:(NSArray <NSURL *>*)paths destnation:(NSURL *)outputURL finish:(JHAudioToolFinishBlock)finish
{
    if (paths.count == 0 || outputURL == nil) {
        return;
    }
    
    AVMutableComposition *composition = [AVMutableComposition composition];
    // 设置音频合并音轨
    AVMutableCompositionTrack *compositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    // 开始时间
    CMTime beginTime = kCMTimeZero;
    NSError *error = nil;
    for (NSURL *url in paths) {
        // 音频文件资源
        AVURLAsset *asset = [AVURLAsset assetWithURL:url];
        // 需要合并的音频文件的区间
        CMTimeRange timeRange = CMTimeRangeMake(kCMTimeZero, asset.duration);
        // ofTrack 音频文件内容
        AVAssetTrack *track = [asset tracksWithMediaType:AVMediaTypeAudio].firstObject;
        //
        [compositionTrack insertTimeRange:timeRange ofTrack:track atTime:beginTime error:&error];
        if (error) {
            NSLog(@"error:%@",error);
        }
        
        beginTime = CMTimeAdd(beginTime, asset.duration);
    }
    
    [[NSFileManager defaultManager] removeItemAtURL:outputURL error:nil];
    
    // 导出合并的音频
    // presetName 与 outputFileType 要对应
    AVAssetExportSession *export = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetAppleM4A];
    export.outputURL = outputURL;
    export.outputFileType = AVFileTypeAppleM4A;
    export.shouldOptimizeForNetworkUse = YES;
    [export exportAsynchronouslyWithCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (finish) {
                if(export.status == AVAssetExportSessionStatusCompleted) {
                    AVURLAsset *asset = [AVURLAsset assetWithURL:outputURL];
                    int64_t seconds = asset.duration.value / asset.duration.timescale;
                    
                    finish(YES, seconds);
                }else if(export.status == AVAssetExportSessionStatusFailed){
                    NSLog(@"export failed:%@",error);
                    finish(NO, 0);
                }
            }
        });
    }];
}

猜你喜欢

转载自blog.csdn.net/xjh093/article/details/85163304
今日推荐