問題背景
unity 2019.4.18f1下使用videoplayer動(dòng)態(tài)播放mp4視頻,在win10環(huán)境下苔悦,不管是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
其中可以看到視頻參數(shù)是RFC6381 Codec Parameters: avc1.42C01E
,不過并不是所有MP4都是這個(gè)參數(shù)伐蒋,有的是RFC6381 Codec Parameters: mp4v.20.1
工三。咱對這codec不熟,在微軟官網(wǎng)上看到MP4好幾個(gè)格式的要求也僅僅是win7:
image.png
事實(shí)也是如此咽弦,這些視頻在win7上是可以播放的徒蟆,比如用win7自帶的Windows Media Player,但在unity里就不行型型,那說明應(yīng)該不是系統(tǒng)本身不支持段审,而是unity的原因。
而后看到下面這篇文章:https://blog.csdn.net/EverNess010/article/details/80684724
其中提到將win7升級(jí)到sp1闹蒜,經(jīng)確認(rèn)寺枉,測試使用的win7本來就是sp1,而上圖也已經(jīng)表明win7是支持MP4的绷落,和系統(tǒng)無關(guān)姥闪。
將視頻編碼改為vp8呢?經(jīng)過測試確實(shí)可行砌烁,不管在win10還是win7上均可播放筐喳。
image.png
于是,解決方法便是函喉,寫一個(gè)腳本來自動(dòng)處理避归,導(dǎo)入MP4時(shí)將其編碼改為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
{
// ... 處理其他類型資源
}
}