音频的截取

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


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);


            }

        });



    }];


}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容