使用AVAssetExportSession修剪iOS 7中的音频文件会给出错误的持续时间

使用AVAssetExportSession修剪iOS 7中的音频文件会给出错误的持续时间,ios,audio,ios7,trim,avassetexportsession,Ios,Audio,Ios7,Trim,Avassetexportsession,我有一个用户将被允许在提交到服务器之前修剪音频文件的要求。修剪功能在iOS 6中可以正常工作,而在iOS 7中则不行 在iOS 7中,当用户从iTunes库中选择一首歌曲并开始修剪时,就会发生这种情况。它看起来像是修剪过的。修剪后创建的新文件将播放到修剪,其余文件将为空。此外,持续时间显示原始歌曲的持续时间。并非所有文件都会发生这种情况。这种情况只发生在某些文件中。此外,我还检查了可导出内容和hasProtectedContent。两者都有正确的值(exportable-是,hasProtect

我有一个用户将被允许在提交到服务器之前修剪音频文件的要求。修剪功能在iOS 6中可以正常工作,而在iOS 7中则不行

在iOS 7中,当用户从iTunes库中选择一首歌曲并开始修剪时,就会发生这种情况。它看起来像是修剪过的。修剪后创建的新文件将播放到修剪,其余文件将为空。此外,持续时间显示原始歌曲的持续时间。并非所有文件都会发生这种情况。这种情况只发生在某些文件中。此外,我还检查了可导出内容和hasProtectedContent。两者都有正确的值(exportable-是,hasProtectedContent-否)。我能知道iOS 7中会出现什么问题吗

我正在粘贴音频文件代码以供参考

  - (void)trimAndExportAudio:(AVAsset *)avAsset withDuration:(NSInteger)durationInSeconds withStartTime:(NSInteger)startTime endTime:(NSInteger)endTime toFileName:(NSString *)filename withTrimCompleteBlock:(TrimCompleteBlock)trimCompleteBlock
{
    if (startTime < 0 || startTime > durationInSeconds || startTime >= endTime)
    {
        CGLog(@"start time = %d endTime %d durationInSeconds %d", startTime, endTime, durationInSeconds);

        trimCompleteBlock(NO, @"Invalid Start Time");
        return;
    }
    if (endTime > durationInSeconds)
    {
        CGLog(@"start time = %d endTime %d durationInSeconds %d", startTime, endTime, durationInSeconds);

        trimCompleteBlock(NO, @"Invalid End Time");
        return;
    }

    // create the export session
    AVAssetExportSession *exportSession = [AVAssetExportSession exportSessionWithAsset:avAsset presetName:AVAssetExportPresetAppleM4A];
    if (exportSession == nil)
    {
        trimCompleteBlock(NO, @"Could not create an Export Session.");
        return;
    }

    //export file path
    NSError *removeError = nil;
    NSString *filePath = [[CGUtilities applicationLibraryMyRecordingsDirectory] stringByAppendingPathComponent:filename];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&removeError];
    }
    if (removeError)
    {
        CGLog(@"Error removing existing file = %@", removeError);
    }

    // create trim time range
    CMTime exportStartTime = CMTimeMake(startTime, 1);
    CMTime exportStopTime = CMTimeMake(endTime, 1);
    CMTimeRange exportTimeRange = CMTimeRangeFromTimeToTime(exportStartTime, exportStopTime);

    // configure export session  output with all our parameters
    exportSession.outputURL = [NSURL fileURLWithPath:filePath];     // output path
    exportSession.outputFileType = AVFileTypeAppleM4A;              // output file type
    exportSession.timeRange = exportTimeRange;                      // trim time range

    //perform the export
    __weak AVAssetExportSession *weakExportSession = exportSession;
    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        if (AVAssetExportSessionStatusCompleted == exportSession.status)
        {
            if (![filename isEqualToString:kLibraryTempFileName])
            {
                //created a new recording
            }

            trimCompleteBlock(YES, nil);
        }
        else if (AVAssetExportSessionStatusFailed == exportSession.status)
        {
            // a failure may happen because of an event out of your control
            // for example, an interruption like a phone call comming in
            // make sure and handle this case appropriately
            trimCompleteBlock(NO, weakExportSession.error.description);
        }
        else
        {
            trimCompleteBlock(NO, weakExportSession.error.description);
        }
    }];
}
-(void)trimAndExportAudio:(AVAsset*)带持续时间的AVAsset:(NSInteger)持续时间秒带开始时间:(NSInteger)开始时间结束时间:(NSInteger)文件名的结束时间:(NSString*)带TrimCompleteBlock的文件名:(TrimCompleteBlock)TrimCompleteBlock
{
如果(开始时间<0 | |开始时间>持续时间秒| |开始时间>=结束时间)
{
CGLog(@“开始时间=%d结束时间%d持续时间秒%d”,开始时间,结束时间,持续时间秒);
TrimpleteBlock(否,@“无效启动时间”);
回来
}
如果(结束时间>持续时间秒)
{
CGLog(@“开始时间=%d结束时间%d持续时间秒%d”,开始时间,结束时间,持续时间秒);
TrimpleteBlock(否,@“无效结束时间”);
回来
}
//创建导出会话
AVAssetExportSession*exportSession=[AvassetExportSessionWithAsset:avAsset预设名称:AVAssetExportPresetAppleM4A];
if(exportSession==nil)
{
trimCompleteBlock(否,@“无法创建导出会话”);
回来
}
//导出文件路径
n错误*删除错误=nil;
NSString*filePath=[[CGUtilities applicationLibraryMyRecordingsDirectory]stringByAppendingPathComponent:filename];
if([[NSFileManager defaultManager]fileExistsAtPath:filePath])
{
[[NSFileManager defaultManager]removeItemAtPath:filePath错误:&removeError];
}
如果(删除错误)
{
CGLog(@“删除现有文件时出错=%@”,删除错误);
}
//创建修剪时间范围
CMTime exportStartTime=CMTimeMake(startTime,1);
CMTime EXPORTSOPTIME=CMTimeMake(结束时间,1);
CMTimeRange exportTimeRange=CMTimeRangeFromTimeToTime(exportStartTime,exportStopTime);
//使用所有参数配置导出会话输出
exportSession.outputURL=[NSURL fileURLWithPath:filePath];//输出路径
exportSession.outputFileType=AVFileTypeAppleM4A;//输出文件类型
exportSession.timeRange=exportTimeRange;//修剪时间范围
//执行导出
__弱AVAssetExportSession*弱exportSession=exportSession;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
if(AVAssetExportSessionStatusCompleted==exportSession.status)
{
如果(![filename IsequalString:kLibraryTempFileName])
{
//创建了一个新的录音
}
TrimpleteBlock(是,无);
}
else if(AVAssetExportSessionStatusFailed==exportSession.status)
{
//由于您无法控制的事件,可能会发生故障
//例如,一个像电话一样的中断即将到来
//确保并妥善处理此案例
TrimpleteBlock(否,weakExportSession.error.description);
}
其他的
{
TrimpleteBlock(否,weakExportSession.error.description);
}
}];
}

谢谢

我们可以导入AVFoundation/AVFoundation.h

-(BOOL)trimAudiofile{

    float audioStartTime;//define start time of audio
    float audioEndTime;//define end time of audio
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
   [dateFormatter setDateFormat:@"yyyy-MM-dd_HH-mm-ss"];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *libraryCachesDirectory = [paths objectAtIndex:0];
   libraryCachesDirectory = [libraryCachesDirectory stringByAppendingPathComponent:@"Caches"];
    NSString *OutputFilePath = [libraryCachesDirectory stringByAppendingFormat:@"/output_%@.mp4", [dateFormatter stringFromDate:[NSDate date]]];
   NSURL *audioFileOutput = [NSURL fileURLWithPath:OutputFilePath];
   NSURL *audioFileInput;//<Path of orignal audio file>

   if (!audioFileInput || !audioFileOutput)
   {
       return NO;
   }

   [[NSFileManager defaultManager] removeItemAtURL:audioFileOutput error:NULL];
   AVAsset *asset = [AVAsset assetWithURL:audioFileInput];

   AVAssetExportSession *exportSession = [AVAssetExportSession exportSessionWithAsset:asset
                                                                        presetName:AVAssetExportPresetAppleM4A];
   if (exportSession == nil)
   {
       return NO;
   }
   CMTime startTime = CMTimeMake((int)(floor(audioStartTime * 100)), 100);
   CMTime stopTime = CMTimeMake((int)(ceil(audioEndTime * 100)), 100);
   CMTimeRange exportTimeRange = CMTimeRangeFromTimeToTime(startTime, stopTime);

   exportSession.outputURL = audioFileOutput;
   exportSession.timeRange = exportTimeRange;
   exportSession.outputFileType = AVFileTypeAppleM4A;

   [exportSession exportAsynchronouslyWithCompletionHandler:^
   {
       if (AVAssetExportSessionStatusCompleted == exportSession.status)
       {
           NSLog(@"Export OK");
       }
       else if (AVAssetExportSessionStatusFailed == exportSession.status)
       {
           NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]);
       }
   }];
  return YES;
}
-(BOOL)音频文件{
float audioStartTime;//定义音频的开始时间
float audioEndTime;//定义音频的结束时间
NSDateFormatter*dateFormatter=[[NSDateFormatter alloc]init];
[日期格式化程序setDateFormat:@“yyyy-MM-dd_HH-MM-ss”];
NSArray*Path=NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,是);
NSString*libraryCachesDirectory=[paths objectAtIndex:0];
libraryCachesDirectory=[libraryCachesDirectory stringByAppendingPathComponent:@“Caches”];
NSString*OutputFilePath=[LibraryCacheSDirectoryStringByAppendingFormat:@”/output%@.mp4“,[dateFormatter stringFromDate:[NSDate date]];
NSURL*audioFileOutput=[NSURL fileURLWithPath:OutputFilePath];
NSURL*音频文件输入//
如果(!audioFileInput | |!audioFileOutput)
{
返回否;
}
[[NSFileManager defaultManager]RemoveItemAttribute:audioFileOutput错误:NULL];
AVAsset*asset=[AVAsset AssetWithur:audioFileInput];
AVAssetExportSession*exportSession=[AvassetExportSessionWithAsset:asset
预设名称:AVAssetExportPresetAppleM4A];
if(exportSession==nil)
{
返回否;
}
CMTime startTime=CMTimeMake((int)(地板(音频startTime*100)),100);
CMTime stopTime=CMTimeMake((int)(ceil(audioEndTime*100)),100);
CMTimeRange exportTimeRange=CMTimeRangeFromTimeToTime(开始时间、停止时间);
exportSession.outputURL=音频文件输出;
exportSession.timeRange=exportTimeRange;
exportSession.outputFileType=AVFileTypeAppleM4A;
[exportSession exportAsynchronouslyWithCompletionHandler:^
{
if(AVAssetExportSessionStatusCompleted==exportSession.status)
{
NSLog(“导出正常”);
}
else if(AVAssetExportSessionStatusFailed==exportSession.status)
{
NSLog(@“导出失败:%@,[[exportSession error]localizedDescription]);
}
}];
返回YES;
}

我们可以导入AVFoundation/AVFoundation.h

-(BOOL)trimAudiofile{

    float audioStartTime;//define start time of audio
    float audioEndTime;//define end time of audio
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
   [dateFormatter setDateFormat:@"yyyy-MM-dd_HH-mm-ss"];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *libraryCachesDirectory = [paths objectAtIndex:0];
   libraryCachesDirectory = [libraryCachesDirectory stringByAppendingPathComponent:@"Caches"];
    NSString *OutputFilePath = [libraryCachesDirectory stringByAppendingFormat:@"/output_%@.mp4", [dateFormatter stringFromDate:[NSDate date]]];
   NSURL *audioFileOutput = [NSURL fileURLWithPath:OutputFilePath];
   NSURL *audioFileInput;//<Path of orignal audio file>

   if (!audioFileInput || !audioFileOutput)
   {
       return NO;
   }

   [[NSFileManager defaultManager] removeItemAtURL:audioFileOutput error:NULL];
   AVAsset *asset = [AVAsset assetWithURL:audioFileInput];

   AVAssetExportSession *exportSession = [AVAssetExportSession exportSessionWithAsset:asset
                                                                        presetName:AVAssetExportPresetAppleM4A];
   if (exportSession == nil)
   {
       return NO;
   }
   CMTime startTime = CMTimeMake((int)(floor(audioStartTime * 100)), 100);
   CMTime stopTime = CMTimeMake((int)(ceil(audioEndTime * 100)), 100);
   CMTimeRange exportTimeRange = CMTimeRangeFromTimeToTime(startTime, stopTime);

   exportSession.outputURL = audioFileOutput;
   exportSession.timeRange = exportTimeRange;
   exportSession.outputFileType = AVFileTypeAppleM4A;

   [exportSession exportAsynchronouslyWithCompletionHandler:^
   {
       if (AVAssetExportSessionStatusCompleted == exportSession.status)
       {
           NSLog(@"Export OK");
       }
       else if (AVAssetExportSessionStatusFailed == exportSession.status)
       {
           NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]);
       }
   }];
  return YES;
}
-(BOOL)音频文件{
float audioStartTime;//定义音频的开始时间
float audioEndTime;//定义结束时间o