我想将应用程序文档文件夹中的 MP4 文件转换为音频文件(mp3 或 m4a)。
我已经试过了,但是我不能用 AVPlayer 播放转换后的 MP3 文件。
这是我的代码:
-(void)convertMP4toMP3withFileNSString*)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];
}
}];
}
有没有人可以解决我的问题或可以改进我的代码?
Best Answer-推荐答案 strong>
替换这一行:
exportSesh.outputFileType = AVFileTypeAppleM4A;
与:
exportSesh.outputFileType = AVFileTypeCoreAudioFormat;
&这个:
NSString *toPathString = [NSString stringWithFormat"%@/testfile.m4a", onlyPath];
与:
NSString *toPathString = [NSString stringWithFormat"%@/testfile.mp3", onlyPath];
为我工作
关于ios - Xcode:如何将 MP4 文件转换为音频文件,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/27590510/
|