美文网首页
音频的截取

音频的截取

作者: 泥孩儿0107 | 来源:发表于2018-09-13 11:27 被阅读0次

和在视频中获取音频方式差不多

if (self.totalTime >=_cutendTime) {

         __weaktypeof(self) weakSelf =self;

        NSArray  *paths =NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);

        NSString*path=[pathsobjectAtIndex:0];

        //NSString *movDirectory = [path stringByAppendingPathComponent:@"/%@.m4a"];

        NSString* movDirectory =  [pathstringByAppendingPathComponent:

                                    [NSStringstringWithFormat:@"/%@.m4a",[selfgetCurrentTimes]]];

        //self.confirmBlock(self->_cutstartTime, self->_cutendTime);

        [self exportPath:movDirectory withFilePath:self.musicPath withStartTime:_cutstartTime withEndTime:(int64_t)_cutendTime withBlock:^(BOOL ret) {

            __strongtypeof(weakSelf) strongSelf = weakSelf;

            weakSelf.confirmBlock(strongSelf->_cutstartTime, strongSelf->_cutendTime);

        }];

    }

// 支持音频:m4a  视频:mp4

-(void)setUpAndAddAudioAtPath:(AVURLAsset*)songAsset toComposition:(AVMutableComposition*)composition start:(CMTime)start dura:(CMTime)dura offset:(CMTime)offset andArray:(NSMutableArray*)audioMixParams{

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

    AVAssetTrack *sourceAudioTrack = [[songAsset tracksWithMediaType:AVMediaTypeAudio]objectAtIndex:0];

    NSError*error =nil;

    BOOLok =NO;

    CMTimestartTime = start;

    CMTimetrackDuration = dura;

    CMTimeRangetRange =CMTimeRangeMake(startTime,trackDuration);

    //设置音量

    //AVMutableAudioMixInputParameters(输入参数可变的音频混合)

    //audioMixInputParametersWithTrack(音频混音输入参数与轨道)

    //AVMutableAudioMixInputParameters *trackMix = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:track];

    //[trackMix setVolume:0.8f atTime:startTime];

    //素材加入数组

    //[audioMixParams addObject:trackMix];

    //Insert audio into track  //offsetCMTimeMake(0, 44100)

    ok =  [trackinsertTimeRange:tRangeofTrack:sourceAudioTrackatTime:kCMTimeInvaliderror:&error];

}

- (void)exportPath:(NSString *)exportPath

      withFilePath:(NSString *)filePath

     withStartTime:(int64_t)startTime

       withEndTime:(int64_t)endTime

         withBlock:(success)handle

{

    _block= handle;

    NSString*presetName;

    NSString*outputFileType;

     if ([filePath.lastPathComponent containsString:@"m4a"]){

        presetName =AVAssetExportPresetAppleM4A;

        outputFileType =AVFileTypeAppleM4A;

    }else{

        _block(NO);  return;

    }

    // 1.拿到预处理音频文件

    NSURL*songURL = [NSURLfileURLWithPath:filePath];

    AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:songURL options:nil];

    // 2.创建新的音频文件

    if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath]) {

        [[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];

    }

    CMTime_startTime =CMTimeMake(startTime,1);

    CMTime_stopTime =CMTimeMake(endTime,1);

    AVMutableComposition *composition =[AVMutableComposition composition];

    NSMutableArray *audioMixParams = [NSMutableArray array];

    //获取视频中的音频素材

    [selfsetUpAndAddAudioAtPath:songAssettoComposition:compositionstart:_startTimedura:_stopTimeoffset:CMTimeMake(14*44100,44100)andArray:audioMixParams];

    //创建一个可变的音频混合

    AVMutableAudioMix *audioMix =[AVMutableAudioMix audioMix];

    audioMix.inputParameters =[NSArray arrayWithArray:audioMixParams];//从数组里取出处理后的音频轨道参数

    //创建一个输出

    AVAssetExportSession *exporter =[[AVAssetExportSession alloc]

                                     initWithAsset:composition

                                     presetName:AVAssetExportPresetAppleM4A];

    exporter.audioMix= audioMix;

    exporter.outputFileType=@"com.apple.m4a-audio";

    //视频的声音,合成后存储

//    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);

//    NSString*path=[paths objectAtIndex:0];

//

//

//    NSString * movDirectory =  [path stringByAppendingPathComponent:

//                                [NSString stringWithFormat:@"/%@.m4a",[self getCurrentTimes]]];

    if([[NSFileManager defaultManager]fileExistsAtPath:exportPath]) {

        [[NSFileManager defaultManager]removeItemAtPath:exportPath error:nil];

    }

    NSURL*exportURL =[NSURLfileURLWithPath:exportPath];

    exporter.outputURL= exportURL;

    MAKAudioObject * object = [[MAKAudioObject alloc]init];

    object.url= exportPath;

    object.name= [exportPathsubstringFromIndex:exportPath.length-19];

    object.localam  = [exportPathsubstringFromIndex:exportPath.length-19];

     __weaktypeof(self) weakSelf =self;

    [exporterexportAsynchronouslyWithCompletionHandler:^{

        __strongtypeof(weakSelf) strongSelf = weakSelf;

        dispatch_async(dispatch_get_main_queue(), ^{

            NSLog(@"Export status not yet completed. Error: %@", exporter.error.description);

            if (exporter.status == AVAssetExportSessionStatusCompleted) {

                NSURL*songURL = [NSURLfileURLWithPath:exportPath];

                AVURLAsset*songAsset = [AVURLAssetURLAssetWithURL:songURLoptions:nil];

                object.time =[NSString stringWithFormat:@"%.2f",CMTimeGetSeconds(songAsset.duration)];

                NSData* data = [NSDatadataWithContentsOfFile:exportPath];

                NSLog(@"data:%@",data);

                NSNumber*size;

                [songAsset.URL getResourceValue:&size forKey:NSURLFileSizeKey error:nil];

                NSLog(@"size is %.2f",[sizefloatValue]/(1024.0*1024.0));//size is 43.703005

                object.cunchu=[NSStringstringWithFormat:@"%.2fMb",[sizefloatValue]/(1024.0*1024.0)];

                if ( [[MAKAudioMusicDBManager sharedManager] insertAudioWith:object]) {

                  strongSelf->_block(YES);

                }else{

               strongSelf->_block(NO);

                }

            }else{

             strongSelf->_block(NO);

            }

        });

    }];

}

相关文章

网友评论

      本文标题:音频的截取

      本文链接:https://www.haomeiwen.com/subject/dmhwgftx.html