관리 메뉴

caLAB

[유니티 개발]비디오 플레이어에서 audioSource 받아오기 본문

Unity/유니티 개발

[유니티 개발]비디오 플레이어에서 audioSource 받아오기

도이(doi) 2021. 11. 21. 15:56
728x90

[RequireComponent(typeof(AudioSource))]

void getVideoAudioSource()
    {
        _audioSource = GetComponent<AudioSource>();
        video.audioOutputMode = VideoAudioOutputMode.AudioSource; //audio source 모드로 설정
        video.EnableAudioTrack(0, true); //첫 번재 track을 사용
        video.SetTargetAudioSource(0, _audioSource); //첫 번재 track에 audio source 설정
    }

Audio Spectrum 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Video;

[RequireComponent(typeof(AudioSource))]
public class audioSpectrum : MonoBehaviour
{
    public VideoPlayer video;
    private AudioSource _audioSource;
    public static float[] _samples = new float[512];
    public static float[] _freqBand = new float[8];

    private void Start()
    {
        getVideoAudioSource();
    }

    private void Update()
    {
        GetSpectrumAudioSouce();
        MakeFrequencyBands();
    }

    void getVideoAudioSource()
    {
        _audioSource = GetComponent<AudioSource>();
        video.audioOutputMode = VideoAudioOutputMode.AudioSource;
        video.EnableAudioTrack(0, true);
        video.SetTargetAudioSource(0, _audioSource);
    }

    void GetSpectrumAudioSouce()
    {
        _audioSource.GetSpectrumData(_samples, 0, FFTWindow.Blackman);
    }

    void MakeFrequencyBands()
    {
        int count = 0;

        for(int i=0; i<8; i++)
        {
            float average = 0;
            int sampleCount = (int)Mathf.Pow(2, i) * 2;

            if (i == 7)
            {
                sampleCount += 2;
            }
            for(int j=0; j<sampleCount; j++)
            {
                average += _samples[count] * (count + 1);
                count++;
            }

            average /= count;
            _freqBand[i] = average * 10;
        }
    }
}

play on awake와 loop를 꺼줘야 된다.

728x90
반응형
Comments