Похоже, что есть миллион сообщений на эту тему, но я пробовал каждое решение, которое я могу найти в каждой теме, которую я прочитал, и оно все еще не работает для меня.По сути, у меня есть скрипт, который добавляет компонент видеопроигрывателя к игровому объекту и устанавливает все необходимые значения, а затем воспроизводит его.
Большая часть того, что я прочитал в Интернете, говорит мне, что я должен добавить этот код, чтобы звук работал:
videoPlayer.controlledAudioTrackCount = 1;
videoPlayer.EnableAudioTrack(0, true);
videoPlayer.SetTargetAudioSource(0, audioSource);
И что я должен добавить вышеупомянутый блок кода перед videoPlayer.Prepare ().К сожалению, это все еще не работает.Поэтому я предоставляю свой сценарий на случай, если кто-нибудь найдет мою ошибку и поможет мне.
Вот она.Это все дело.Извините, если это долго, но я не уверен, в чем проблема, поэтому я решил, что должен предоставить больше информации на случай, если это то, чего я не ожидал.Есть несколько обращений к другим сценариям, но они незначительны и не должны влиять на вашу способность понимать природу сценария:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Video;
using Ibuprogames.CameraTransitionsAsset;
public class PlayVideoScript : MonoBehaviour
{
private CrossFade crossFade;
private GameManagerScript gameManager;
private CameraTransition cameraTransition;
private VideoPlayer videoPlayer;
private SpriteRenderer bgdSR;
public VideoClip videoClip;
public enum TargetAudioSource { SFX, Music, Master }
public TargetAudioSource targetAudioSource;
public bool interruptMusic = false; //Only applicable if Music Audio Source is selected
private Camera thisCamera;
public Camera destinationCamera;
public enum TransitionToNewCamera { Cut, Crossfade, PanLeft, PanRight, PanUp, PanDown, CrossZoom }
public TransitionToNewCamera transition;
private AudioSource audioSource;
private bool videoDone;
private Camera[] allCams;
private bool videoPrepared;
AudioSource master1;
AudioSource m1;
AudioSource m2;
AudioSource sfx1;
private void Awake()
{
SetCamera();
if (thisCamera == null)
{
Debug.LogError("thisCamera is null in PlayVideoScript");
}
master1 = GameObject.Find("Master Audio Source").GetComponent<AudioSource>();
m1 = GameObject.Find("Music Audio Source 1").GetComponent<AudioSource>();
m2 = GameObject.Find("Music Audio Source 2").GetComponent<AudioSource>();
sfx1 = GameObject.Find("SFX Audio Source 1").GetComponent<AudioSource>();
bgdSR = gameObject.transform.parent.transform.parent.Find("Background").GetComponent<SpriteRenderer>();
gameManager = GameObject.Find("GameManager").GetComponent<GameManagerScript>();
crossFade = GameObject.Find("GameManager").GetComponent<CrossFade>();
if (cameraTransition == null)
{
cameraTransition = FindObjectOfType<CameraTransition>();
}
CreateVideoPlayer();
}
private void Start()
{
videoPlayer.loopPointReached += EndReached;
videoPlayer.prepareCompleted += PlayVideo;
}
// Update is called once per frame
void Update()
{
if (videoDone)
{
GameManagerScript.originalCamera = thisCamera;
GameManagerScript.destinationCamera = destinationCamera;
switch (transition)
{
case TransitionToNewCamera.Cut:
thisCamera.gameObject.SetActive(false);
destinationCamera.gameObject.SetActive(true);
break;
case TransitionToNewCamera.Crossfade:
crossFade.CrossFadeTransition(thisCamera, destinationCamera, 1);
break;
case TransitionToNewCamera.PanLeft:
crossFade.PanTransitionHorizontal(thisCamera, destinationCamera, false, gameManager.transSpeedSlider.value);
break;
case TransitionToNewCamera.PanRight:
crossFade.PanTransitionHorizontal(thisCamera, destinationCamera, true, gameManager.transSpeedSlider.value);
break;
case TransitionToNewCamera.PanUp:
crossFade.PanTransitionVertical(thisCamera, destinationCamera, true, gameManager.transSpeedSlider.value);
break;
case TransitionToNewCamera.PanDown:
crossFade.PanTransitionVertical(thisCamera, destinationCamera, false, gameManager.transSpeedSlider.value);
break;
case TransitionToNewCamera.CrossZoom:
cameraTransition.DoTransition(CameraTransitionEffects.CrossZoom, thisCamera, destinationCamera, 1.0f, false);
break;
}
videoDone = false;
}
}
private void OnMouseUpAsButton()
{
if (videoPlayer == null)
{
CreateVideoPlayer();
}
if (thisCamera == null)
{
SetCamera();
}
switch (targetAudioSource)
{
case TargetAudioSource.Master:
audioSource = master1;
audioSource.volume = Mathf.Clamp01(Mathf.InverseLerp(gameManager.masterVolumeSlider.minValue, gameManager.masterVolumeSlider.maxValue, gameManager.masterVolumeSlider.value));
break;
case TargetAudioSource.Music:
audioSource.volume = Mathf.Clamp01(Mathf.InverseLerp(gameManager.musicVolumeSlider.minValue, gameManager.musicVolumeSlider.maxValue, gameManager.musicVolumeSlider.value));
if (interruptMusic)
{
if (m1.isPlaying)
{
audioSource = m1;
}
else
{
audioSource = m2;
}
}
else if (!interruptMusic)
{
if (m2.isPlaying)
{
audioSource = m1;
}
else
{
audioSource = m2;
}
}
break;
case TargetAudioSource.SFX:
audioSource = sfx1;
audioSource.volume = GameManagerScript.sfxVolume;
break;
}
videoPlayer.controlledAudioTrackCount = 1;
videoPlayer.EnableAudioTrack(0, true);
videoPlayer.SetTargetAudioSource(0, audioSource);
audioSource.clip = null;
videoPlayer.frame = 0;
videoPlayer.Prepare();
}
void PlayVideo(VideoPlayer player)
{
videoPlayer.Play();
audioSource.Play();
StartCoroutine(DelayVideo());
}
IEnumerator DelayVideo()
{
const int numFramesDelay = 8;
for (int i = 0; i < numFramesDelay; i++)
{
yield return null;
}
bgdSR.enabled = false;
}
void CreateVideoPlayer()
{
if (gameObject.GetComponent<VideoPlayer>() != null)
{
videoPlayer = bgdSR.gameObject.GetComponent<VideoPlayer>();
}
else
{
videoPlayer = bgdSR.gameObject.AddComponent<VideoPlayer>() as VideoPlayer;
}
videoPlayer.source = VideoSource.VideoClip;
videoPlayer.playOnAwake = false;
videoPlayer.clip = videoClip;
videoPlayer.audioOutputMode = VideoAudioOutputMode.AudioSource;
videoPlayer.isLooping = false;
videoPlayer.renderMode = VideoRenderMode.CameraFarPlane;
videoPlayer.targetCamera = thisCamera;
videoPlayer.enabled = true;
} //--End CreateVideoPlayer()
void SetCamera()
{
allCams = Resources.FindObjectsOfTypeAll<Camera>();
foreach (Camera c in allCams)
{
if (c.transform.parent == transform.parent.transform.parent)
{
thisCamera = c;
}
}
}
void EndReached(VideoPlayer player)
{
audioSource.Stop();
videoPlayer.Pause();
audioSource.volume = 0;
videoDone = true;
}
}
Есть одна вещь, которую я подозреваю, может иметь какое-то отношение кэто то, что я должен установить аудиоклип на нуль, так как я использую тот же AudioSource для воспроизведения других вещей в сцене.Если я не очищаю его, он просто воспроизводит то, что было воспроизведено последним.
Как мне установить клип при использовании его для видеоплеера?