问题背景
unity 2019.4.18f1下使用videoplayer动态播放mp4视频,在win10环境下,不管是Editor,还是打包出来的PC包,均可正常播放。但在win7电脑上播放不出来。
解决过程
直觉上怀疑是解码问题。视频是策划用QQ录屏录制的mp4,先用MP4Box查看下视频信息。
mp4box -info G:\muweb\trunk\project\Assets\AssetSources\video\500545.mp4
# Movie Info - 2 tracks - TimeScale 1000
Duration 00:00:01.200
Fragmented: no
Major Brand isom - version 512 - compatible brands: isom iso2 avc1 mp41
Created: UNKNOWN DATE
iTunes Info:
tool: Lavf57.2.102
# Track 1 Info - ID 1 - TimeScale 15360
Media Duration 00:00:01.200
Track has 1 edits: track duration is 00:00:01.200
Track flags: Enabled In Movie
Media Info: Language "Undetermined (und)" - Type "vide:avc1" - 36 samples
Visual Sample Entry Info: width=488 height=550 (depth=24 bits)
Visual Track layout: x=0 y=0 width=488 height=550
AVC/H264 Video - Visual Size 488 x 550
AVC Info: 1 SPS - 1 PPS - Profile Baseline @ Level 3
NAL Unit length bits: 32
Chroma format YUV 4:2:0 - Luma bit depth 8 - chroma bit depth 8
SPS#1 hash: EF6F62B13BA263A64FB8D30358F6037AF8DD720F
PPS#1 hash: B45CE09D3615D8C80B755072D5E3307FDF18CB4E
RFC6381 Codec Parameters: avc1.42C01E
Only one sync sample
Max sample duration: 512 / 15360
# Track 2 Info - ID 2 - TimeScale 48000
Media Duration 00:00:00.630
Track has 1 edits: track duration is 00:00:00.597
Track flags: Enabled In Movie
Media Info: Language "Undetermined (und)" - Type "soun:mp4a" - 30 samples
Alternate Group ID 1
MPEG-4 Audio AAC LC (AOT=2 implicit) - 2 Channel(s) - SampleRate 48000
RFC6381 Codec Parameters: mp4a.40.2
All samples are sync
Max sample duration: 1024 / 48000
其中可以看到视频参数是RFC6381 Codec Parameters: avc1.42C01E
,不过并不是所有MP4都是这个参数,有的是RFC6381 Codec Parameters: mp4v.20.1
。咱对这codec不熟,在微软官网上看到MP4好几个格式的要求也仅仅是win7:
事实也是如此,这些视频在win7上是可以播放的,比如用win7自带的Windows Media Player,但在unity里就不行,那说明应该不是系统本身不支持,而是unity的原因。
而后看到下面这篇文章:https://blog.csdn.net/EverNess010/article/details/80684724
其中提到将win7升级到sp1,经确认,测试使用的win7本来就是sp1,而上图也已经表明win7是支持MP4的,和系统无关。
将视频编码改为vp8呢?经过测试确实可行,不管在win10还是win7上均可播放。
于是,解决方法便是,写一个脚本来自动处理,导入MP4时将其编码改为vp8,如下所示:
using UnityEngine;
using UnityEditor;
using System.IO;
public class AssetPostprocessorEx : AssetPostprocessor
{
static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
for (int i = 0; i < movedAssets.Length; i++)
{
AssetDatabase.ImportAsset(movedAssets[i]);
}
}
void OnPreprocessAsset()
{
var type = assetImporter.GetType();
if (type == typeof(VideoClipImporter))
{
VideoClipImporter import = (VideoClipImporter)assetImporter;
var setting = import.defaultTargetSettings;
setting.enableTranscoding = true;
setting.codec = UnityEditor.VideoCodec.VP8;
import.defaultTargetSettings = setting;
}
else
{
// ... 处理其他类型资源
}
}