0
float vocalStartMarker = 1.0;
    float vocalEndMarker = 3.0;
    NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSURL *audioFileInput =[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/idea_honey_bunny.mp3", [[NSBundle mainBundle] resourcePath]]];



       NSURL *audioFileOutput =[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/idea_honey_bunny.mp3", [[NSBundle mainBundle] resourcePath]]];

    NSError *error;

    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(vocalStartMarker * 1)), 1);
    CMTime stopTime = CMTimeMake((int)(ceil(vocalEndMarker * 1)), 1);
    CMTimeRange exportTimeRange = CMTimeRangeFromTimeToTime(startTime, stopTime);

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

    [exportSession exportAsynchronouslyWithCompletionHandler:^
     {
         if (AVAssetExportSessionStatusCompleted == exportSession.status)
         {
             NSLog(@"It worked!");
         }
         else if (AVAssetExportSessionStatusFailed == exportSession.status)
         {
             // It failed...
         }
     }];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileOutput error:&error];
    //  audioPlayer.numberOfLoops = -1;

    if (audioPlayer == nil)
        NSLog(@"%@",error);
    else
        [audioPlayer play];
    return YES;
}

我想尝试修剪音频文件,但如果(AVAssetExportSessionStatusCompleted == exportSession.status){ NSLog(@“它工作!”);} else if (AVAssetExportSessionStatusFailed == exportSession.status) { // 它失败了... } }]; 块和文件不修剪

4

2 回答 2

0

exportAsynchronouslyWithCompletionHandler方法需要一些时间来导出新资产。因此,您使用尚未准备好的资产创建音频播放器。

尝试像这样更改您的代码

[exportSession exportAsynchronouslyWithCompletionHandler:^
 {
     if (AVAssetExportSessionStatusCompleted == exportSession.status)
     {
        NSLog(@"It worked!");
        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileOutput error:&error];
        if (audioPlayer == nil) {
            NSLog(@"%@",error);
        }
        else {
            [audioPlayer play];
        }
     }
     else if (AVAssetExportSessionStatusFailed == exportSession.status)
     {
         // It failed...
     }
 }];

此外,正如 Murali 上面所说,更改输出文件的路径

于 2013-01-24T11:38:12.540 回答
0

您为 audioFileOutput 和 audioFileInput 提供了相同的路径...所以它会进入失败案例。并且还要确保该文件存在于输入路径中...请更改 OutputFile 路径并检查..

于 2013-01-24T11:34:59.353 回答