Xcode:如何将MP4文件转换为音频文件

时间:2014-12-21 14:54:54

标签: ios xcode file audio

我想将应用程序文档文件夹中的MP4文件转换为音频文件(mp3或m4a)。 我已经尝试了,但我无法使用AVPlayer播放已转换的MP3文件。

这是我的代码:

-(void)convertMP4toMP3withFile:(NSString*)dstPath
{
    NSURL *dstURL = [NSURL fileURLWithPath:dstPath];

AVMutableComposition*   newAudioAsset = [AVMutableComposition composition];

AVMutableCompositionTrack*  dstCompositionTrack;
dstCompositionTrack = [newAudioAsset addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];

AVAsset*    srcAsset = [AVURLAsset URLAssetWithURL:dstURL options:nil];
AVAssetTrack*   srcTrack = [[srcAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];


CMTimeRange timeRange = srcTrack.timeRange;

NSError*    error;

if(NO == [dstCompositionTrack insertTimeRange:timeRange ofTrack:srcTrack atTime:kCMTimeZero error:&error]) {
    NSLog(@"track insert failed: %@\n", error);
    return;
}


AVAssetExportSession*   exportSesh = [[AVAssetExportSession alloc] initWithAsset:newAudioAsset presetName:AVAssetExportPresetPassthrough];

exportSesh.outputFileType = AVFileTypeAppleM4A;
exportSesh.outputURL = dstURL;

[[NSFileManager defaultManager] removeItemAtURL:dstURL error:nil];

[exportSesh exportAsynchronouslyWithCompletionHandler:^{
    AVAssetExportSessionStatus  status = exportSesh.status;
    NSLog(@"exportAsynchronouslyWithCompletionHandler: %i\n", status);

    if(AVAssetExportSessionStatusFailed == status) {
        NSLog(@"FAILURE: %@\n", exportSesh.error);
    } else if(AVAssetExportSessionStatusCompleted == status) {
        NSLog(@"SUCCESS!\n");


        NSError *error;
        //append the name of the file in jpg form

        //check if the file exists (completely unnecessary).
        NSString *onlyPath = [dstPath stringByDeletingLastPathComponent];
        NSString *toPathString = [NSString stringWithFormat:@"%@/testfile.m4a", onlyPath];
        [[NSFileManager defaultManager] moveItemAtPath:dstPath toPath:toPathString error:&error];
        [self loadFiles];
    }
}];
}

有没有人可以解决我的问题,或者可以改进我的代码?

2 个答案:

答案 0 :(得分:1)

替换此行:

exportSesh.outputFileType = AVFileTypeAppleM4A;

使用:

exportSesh.outputFileType = AVFileTypeCoreAudioFormat;

&安培;这个:

NSString *toPathString = [NSString stringWithFormat:@"%@/testfile.m4a", onlyPath];

使用:

NSString *toPathString = [NSString stringWithFormat:@"%@/testfile.mp3", onlyPath];

为我工作:)

答案 1 :(得分:0)

代码确实可以将mp4转换为m4a。也许你的播放音频文件代码是错误的。以下问题可能对您有所帮助。

No sound coming from AVPlayer

iOS Extracting Audio from .mov file