SyncVideoSound.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Video;
  5. namespace Imagine.WebAR.Samples
  6. {
  7. public class SyncVideoSound : MonoBehaviour
  8. {
  9. [SerializeField] VideoPlayer video;
  10. [SerializeField] AudioSource sound;
  11. public float lastPos = 0;
  12. void Awake(){
  13. }
  14. void OnEnable(){
  15. StartCoroutine("SyncRoutine");
  16. }
  17. void OnDisable(){
  18. StopCoroutine("SyncRoutine");
  19. }
  20. IEnumerator SyncRoutine()
  21. {
  22. var videoRenderer = video.GetComponent<Renderer>();
  23. videoRenderer.enabled = false;
  24. while(!video.isPrepared){
  25. Debug.Log("Waiting video preparation");
  26. yield return null;
  27. }
  28. video.Play();
  29. sound.Play();
  30. video.time = lastPos;
  31. //sound.time = lastPos;
  32. while(true){
  33. if(video.time > 0.01f)
  34. {
  35. videoRenderer.enabled = true;
  36. }
  37. else if(!sound.isPlaying){
  38. sound.time = (float)video.time;
  39. sound.Play();
  40. }
  41. if(Mathf.Abs(sound.time - (float)video.time) > 0.1){
  42. Debug.Log(sound.time + ", " + sound.clip.length);
  43. sound.time = (float)video.time;
  44. Debug.Log(sound.time + "=>" + video.time);
  45. }
  46. lastPos = (float)video.time;
  47. //yield return new WaitForSeconds(0.05f);
  48. yield return null;
  49. }
  50. }
  51. }
  52. }