Xcode:如何将MP4文件转换为audio文件

我想要将MP4文件从应用程序的文档文件夹转换成audio文件(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]; } }]; } 

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

replace这一行:

 exportSesh.outputFileType = AVFileTypeAppleM4A; 

有:

 exportSesh.outputFileType = AVFileTypeCoreAudioFormat; 

& 这个:

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

有:

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

为我工作:)

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

没有声音来自AVPlayer

iOS从.mov文件中提取audio