草庐IT

iOS 将 AVI 转换为 MP4

coder 2023-09-30 原文

(请注意我已经看过 this other SO post 了。)

问题

我正在尝试将 avi 视频转换为 mp4,以便我可以使用 Objective-C 在 iOS 应用程序上本地播放它

我尝试过的

我正在尝试使用以下代码进行转换:

- (void)convertVideoToLowQuailtyWithInputURL:(NSURL*)inputURL outputURL:(NSURL*)outputURL handler:(void (^)(AVAssetExportSession*))handler {
    [[NSFileManager defaultManager] removeItemAtURL:outputURL error:nil];
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetHighestQuality];
    exportSession.outputURL = outputURL;
    exportSession.outputFileType = AVFileTypeMPEG4;
    [exportSession exportAsynchronouslyWithCompletionHandler:^(void) {
        handler(exportSession);
    }];
}

从 exportSession 返回的错误是 Cannot Open

额外信息

当我运行试图通过 Mediainfo 转换的视频时,我得到以下视频信息:

7 332kb/s,1920*1080 (16:9),25.000 FPS,AVC (Baseline@L3.1) (CABAC/1 Ref Frames)

这是音频:

128 kb/s,8 000 Hz,16 位,1 channel ,PCM(小/有符号)

我还在 AVAssetExportSession 上使用了 exportPresetsCompatibleWithAsset: 方法并得到了以下结果:

AVAssetExportPreset1920x1080,
AVAssetExportPresetLowQuality,
AVAssetExportPresetAppleM4A,
AVAssetExportPresetHEVCHighestQuality,
AVAssetExportPreset640x480,
AVAssetExportPreset3840x2160,
AVAssetExportPresetHEVC3840x2160,
AVAssetExportPresetHighestQuality,
AVAssetExportPreset1280x720,
AVAssetExportPresetMediumQuality,
AVAssetExportPreset960x540,
AVAssetExportPresetHEVC1920x1080

另一件需要注意的事情是,在使用预设和输出播放时,我设法获得了一个基本上是白噪声的纯音频文件。这是使用预设 AVAssetExportPresetAppleM4A

我希望我记下了足够的信息。

更新

根据 Ashley 的评论,我创建了一个函数来返回与 Assets 兼容的导出设置。

- (void)determineCompatibleExportForAsset:(AVURLAsset *)asset completion:(void(^)(NSArray<ExportSettings *> *exports))handler {
    NSArray<NSString *> *presets = @[
                                     AVAssetExportPresetLowQuality,
                                     AVAssetExportPresetMediumQuality,
                                     AVAssetExportPresetHighestQuality,
                                     AVAssetExportPresetHEVCHighestQuality,
                                     AVAssetExportPreset640x480,
                                     AVAssetExportPreset960x540,
                                     AVAssetExportPreset1280x720,
                                     AVAssetExportPreset1920x1080,
                                     AVAssetExportPreset3840x2160,
                                     AVAssetExportPresetHEVC1920x1080,
                                     AVAssetExportPresetHEVC3840x2160,
                                     AVAssetExportPresetAppleM4A,
                                     AVAssetExportPresetPassthrough
                                     ];

    NSArray<NSString *> *outputs = @[
                                     AVFileTypeQuickTimeMovie,
                                     AVFileTypeMPEG4,
                                     AVFileTypeAppleM4V,
                                     AVFileTypeAppleM4A,
                                     AVFileType3GPP,
                                     AVFileType3GPP2,
                                     AVFileTypeCoreAudioFormat,
                                     AVFileTypeWAVE,
                                     AVFileTypeAIFF,
                                     AVFileTypeAIFC,
                                     AVFileTypeAMR,
                                     AVFileTypeMPEGLayer3,
                                     AVFileTypeSunAU,
                                     AVFileTypeAC3,
                                     AVFileTypeEnhancedAC3,
                                     AVFileTypeJPEG,
                                     AVFileTypeDNG,
                                     AVFileTypeHEIC,
                                     AVFileTypeAVCI,
                                     AVFileTypeHEIF,
                                     AVFileTypeTIFF
                                     ];

    __block int counter = 0;
    int totalCount = (int)presets.count * (int)outputs.count;

    NSMutableArray<ExportSettings *> *exportSettingsArray = [@[] mutableCopy];

    for (NSString *preset in presets) {
        for (NSString *output in outputs) {
            [AVAssetExportSession determineCompatibilityOfExportPreset:preset withAsset:asset outputFileType:output completionHandler:^(BOOL compatible) {
                if (compatible) {
                    ExportSettings *exportSettings = [[ExportSettings alloc] initWithPreset:preset outputType:output];
                    [exportSettingsArray addObject:exportSettings];
                }
                counter++;
                if (counter == totalCount) {
                    if (handler) {
                        handler([exportSettingsArray copy]);
                    }
                }
            }];
        }
    }
}

结果如下:

"Preset: AVAssetExportPresetAppleM4A Output: com.apple.m4a-audio",
"Preset: AVAssetExportPresetPassthrough Output: com.microsoft.waveform-audio",
"Preset: AVAssetExportPresetPassthrough Output: public.aifc-audio",
"Preset: AVAssetExportPresetPassthrough Output: public.aiff-audio",
"Preset: AVAssetExportPresetPassthrough Output: com.apple.coreaudio-format",
"Preset: AVAssetExportPresetPassthrough Output: com.apple.quicktime-movie"

由此我推断,使用预设 AVAssetExportPresetPassthrough 和输出类型 AVFileTypeQuickTimeMovie 是兼容的。

然而,当运行以下代码时:(我已经尝试将 .mp4、.mov 和 .qt 作为文件类型)

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"MyVideo.mov"];
    NSURL *outputURL = [NSURL fileURLWithPath:filePath];
    NSURL *localURL = [NSBundle URLForResource:@"20180626_145233-v" withExtension:@"avi" subdirectory:nil inBundleWithURL:[NSBundle mainBundle].bundleURL];

    [self convertVideoToLowQuailtyWithInputURL:localURL outputURL:outputURL handler:^(AVAssetExportSession *exportSession) {
        switch ([exportSession status]) {
            case AVAssetExportSessionStatusFailed:
                NSLog(@"Export failed: %@", [exportSession error]);
                break;
            case AVAssetExportSessionStatusCancelled:
                NSLog(@"Export canceled");
                break;
            case AVAssetExportSessionStatusCompleted:
                NSLog(@"Successfully");
                 NSLog(@"OutputURL: %@", outputURL.absoluteString);
                break;
            default:
                break;
        }

    }];

调用:

- (void)convertVideoToLowQuailtyWithInputURL:(NSURL*)inputURL outputURL:(NSURL*)outputURL handler:(void (^)(AVAssetExportSession*))handler {
    [[NSFileManager defaultManager] removeItemAtURL:outputURL error:nil];
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:inputURL options:nil];       

    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetPassthrough];
    exportSession.outputURL = outputURL;
    exportSession.outputFileType = AVFileTypeQuickTimeMovie;

    [exportSession exportAsynchronouslyWithCompletionHandler:^(void) {
        handler(exportSession);
    }];
}

我收到这个错误:

导出失败:错误域=AVFoundationErrorDomain 代码=-11800“操作无法完成”UserInfo={NSLocalizedFailureReason=发生未知错误 (-12842),NSLocalizedDescription=操作无法完成,NSUnderlyingError= 0x60400024def0 {Error Domain=NSOSStatusErrorDomain Code=-12842 "(null)"}}

最佳答案

打不开是因为iOS不支持AVI文件

这是 link to the Apple documentation on supported file typesAVFoundation 中。

或者如果值(value)观发生变化,这张图片供后代使用:

最后,您可以从 XCode 中检查 AVFileType 的定义来亲自查看此列表。

就其值(value)而言,cursory inspection on AVI via Google表示 AVI 容器存在一些限制,这些限制已在 iOS 支持的较新格式中得到纠正,因此以后可能没有动力添加支持。

同时也是一个potential issue由于 Microsoft 创建了 AVI,我找不到任何会禁止某人使用它的限制性许可,但是 IANAL。

关于iOS 将 AVI 转换为 MP4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51046842/

有关iOS 将 AVI 转换为 MP4的更多相关文章

  1. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  2. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  3. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  4. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  5. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  6. ruby-on-rails - Ruby url 到 html 链接转换 - 2

    我正在使用Rails构建一个简单的聊天应用程序。当用户输入url时,我希望将其输出为html链接(即“url”)。我想知道在Ruby中是否有任何库或众所周知的方法可以做到这一点。如果没有,我有一些不错的正则表达式示例代码可以使用... 最佳答案 查看auto_linkRails提供的辅助方法。这会将所有URL和电子邮件地址变成可点击的链接(htmlanchor标记)。这是文档中的代码示例。auto_link("Gotohttp://www.rubyonrails.organdsayhellotodavid@loudthinking.

  7. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  8. ruby-on-rails - 使用 ruby​​ 将多个实例变量转换为散列的更好方法? - 2

    我收到格式为的回复#我需要将其转换为哈希值(针对活跃商家)。目前我正在遍历变量并执行此操作:response.instance_variables.eachdo|r|my_hash.merge!(r.to_s.delete("@").intern=>response.instance_eval(r.to_s.delete("@")))end这有效,它将生成{:first="charlie",:last=>"kelly"},但它似乎有点hacky和不稳定。有更好的方法吗?编辑:我刚刚意识到我可以使用instance_variable_get作为该等式的第二部分,但这仍然是主要问题。

  9. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  10. python ffmpeg 使用 pyav 转换 一组图像 到 视频 - 2

    2022/8/4更新支持加入水印水印必须包含透明图像,并且水印图像大小要等于原图像的大小pythonconvert_image_to_video.py-f30-mwatermark.pngim_dirout.mkv2022/6/21更新让命令行参数更加易用新的命令行使用方法pythonconvert_image_to_video.py-f30im_dirout.mkvFFMPEG命令行转换一组JPG图像到视频时,是将这组图像视为MJPG流。我需要转换一组PNG图像到视频,FFMPEG就不认了。pyav内置了ffmpeg库,不需要系统带有ffmpeg工具因此我使用ffmpeg的python包装p

随机推荐