最近老徒弟要畢業了,然後畢設裏unity不能播放視頻聲音。當時我自己測試的時候也是不能正常播放聲音。翻了好久官方API文檔,還是很迷惑。最後Google了下,找到了一個外國友人提供的解決方案。代碼如下:
一.播放指定視頻文件
public class Test : MonoBehaviour {
//Raw Image to Show Video Images [Assign from the Editor]
public RawImage image;
//Video To Play [Assign from the Editor]
public VideoClip videoToPlay;
private VideoPlayer videoPlayer;
private VideoSource videoSource;
//Audio
private AudioSource audioSource;
// Use this for initialization
void Start()
{
//Application.runInBackground = true;
StartCoroutine(playVideo());
}
IEnumerator playVideo()
{
//Add VideoPlayer to the GameObject
videoPlayer = gameObject.AddComponent<VideoPlayer>();
//Add AudioSource
audioSource = gameObject.AddComponent<AudioSource>();
//Disable Play on Awake for both Video and Audio
videoPlayer.playOnAwake = false;
audioSource.playOnAwake = false;
//We want to play from video clip not from url
videoPlayer.source = VideoSource.VideoClip;
//Set video To Play then prepare Audio to prevent Buffering
videoPlayer.clip = videoToPlay;
//Debug.Log("Done Preparing Video");
//Set Audio Output to AudioSource
videoPlayer.audioOutputMode = VideoAudioOutputMode.AudioSource ;
//Assign the Audio from Video to AudioSource to be played
videoPlayer.EnableAudioTrack(0, true);
videoPlayer.SetTargetAudioSource(0, audioSource);
//Google到的解決方案
//這裏一定要讓以上工作完成後才能開始準備videoPlayer 並且賦值視頻輸出Texture
videoPlayer.Prepare();
//Wait until video is prepared
while (!videoPlayer.isPrepared)
{
Debug.Log("Preparing Video");
yield return null;
}
//Set Raw Image to Show Video Images
image.texture = videoPlayer.texture;
//Play Video
videoPlayer.Play();
//Play Sound
audioSource.Play();
//Debug.Log("Playing Video");
while (videoPlayer.isPlaying)
{
Debug.LogWarning("Video Time: " + Mathf.FloorToInt((float)videoPlayer.time));
yield return null;
}
Debug.Log("Done Playing Video");
}
}
查了下管網API,這個Prepare()很重要。只有在準備完成後,視頻的每一幀纔會被立即正確的播放。並且,我們要在播放器屬性設置完之後在調用,不然語音不能被正確播放。
二.從網站地址播放視頻
就是將上面代碼的
//We want to play from video clip not from url
videoPlayer.source = VideoSource.VideoClip;
//Set video To Play then prepare Audio to prevent Buffering
videoPlayer.clip = videoToPlay;
更改爲:
videoPlayer.source = VideoSource.Url;
videoPlayer.url = "http://www.JayW.handsomeboy.mp4";
三.播放本地文件視頻
string url = "file://" + Application.streamingAssetsPath + "/" + "VideoName.mp4";
if !UNITY_EDITOR && UNITY_ANDROID
url = Application.streamingAssetsPath + "/" + "VideoName.mp4";
#endif
//We want to play from url
videoPlayer.source = VideoSource.Url;
videoPlayer.url = url;
四.視頻播放支持的格式所有支持的視頻格式:
- ogv
- vp8
- webm
- mov
- dv
- mp4
- m4v
- mpg
- mpeg
部分Windows上支持的視頻格式:
- avi
- asf
- wmf
Unity的VideoPlayer還支持其他輸出模式,
可根據自身需求參考官方API進行選擇。以上就是VideoPlayer播放視頻的大體內容。希望對你有幫助。