Xcode: How to convert MP4-File to Audio-File

2020-07-27 02:54发布

问题:

I want to convert a MP4-file from the apps Document folder into an Audio-file (mp3 or m4a). I already tried, but i can not play the converted MP3-file with AVPlayer.

Here is my code:

-(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];
    }
}];
}

Has anyone a solution for my problem or can improve my code?

回答1:

replace this line:

exportSesh.outputFileType = AVFileTypeAppleM4A;

with:

exportSesh.outputFileType = AVFileTypeCoreAudioFormat;

& this:

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

with:

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

Worked for me :)



回答2:

The code does work on converting mp4 to m4a. Maybe your play audio file code is wrong. Following questions may be helpful to you.

No sound coming from AVPlayer

iOS Extracting Audio from .mov file