Не удается получить звук для воспроизведения с помощью видеоплеера в сценарии - PullRequest
0 голосов
/ 23 апреля 2019

Похоже, что есть миллион сообщений на эту тему, но я пробовал каждое решение, которое я могу найти в каждой теме, которую я прочитал, и оно все еще не работает для меня.По сути, у меня есть скрипт, который добавляет компонент видеопроигрывателя к игровому объекту и устанавливает все необходимые значения, а затем воспроизводит его.

Большая часть того, что я прочитал в Интернете, говорит мне, что я должен добавить этот код, чтобы звук работал:

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 для воспроизведения других вещей в сцене.Если я не очищаю его, он просто воспроизводит то, что было воспроизведено последним.

Как мне установить клип при использовании его для видеоплеера?

Ответы [ 2 ]

0 голосов
/ 27 апреля 2019

Ну, я сделал oopsie (pewdiepie level lol). Я работаю с командой, и я не знал, что член моей команды, ответственный за видео, еще не закодировал звуковую дорожку. Итак ...

Скрипт действительно работает. Если кто-то ищет сценарий, который добавит видео компонент и воспроизведет видео OnMouseUp (через коллайдер), то это может сэкономить вам время. Примечание: вы не сможете скопировать и вставить все это, потому что я использую ресурсы Unity или пользовательские сценарии, но вы должны быть в состоянии приблизиться.

0 голосов
/ 24 апреля 2019

В вашем OnMouseUpAsButton () вы запускаете Videoplayer, используя функцию CreateVideoplayer, которая устанавливает videoclip.clip. В том же методе [OnMouseUpAsButton] вы устанавливаете клип на null, а frame равняетесь 0. Это похоже на то, когда видеоплеер запускается, он устанавливает клип в функции CreateVideoplayer, а затем устанавливает его клип на null из функции OnMouseUpAsButton. Возможно, вам придется удалить эти 2 строки, и ваш код будет работать нормально.

вот код, который я использую для потокового видео. Создайте класс «[YourClass.cs]» и вставьте код.

public RawImage image;

public VideoClip videoToPlay;

private VideoPlayer videoPlayer;
private VideoSource videoSource;

private AudioSource audioSource;

// Use this for initialization
void Start()
{
    Application.runInBackground = true;
}

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;
    audioSource.Pause();

    //We want to play from video clip not from url

    videoPlayer.source = VideoSource.VideoClip;

    // Vide clip from Url
    //videoPlayer.source = VideoSource.Url;
    //videoPlayer.url = "http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4";


    //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);

    //Set video To Play then prepare Audio to prevent Buffering
    videoPlayer.clip = videoToPlay;
    videoPlayer.Prepare();

    //Wait until video is prepared
    while (!videoPlayer.isPrepared)
    {
        yield return null;
    }

    Debug.Log("Done Preparing Video");

    //Assign the Texture from Video to RawImage to be displayed
    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");
    UIManager.Instance.OnSkipVideo();
}


public void PlayVideo() {
    StartCoroutine(playVideo());

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...