鸟语天空
UGUI—实时频谱效果
post by:追风剑情 2020-12-21 17:39

工程截图

111111.png


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 实时频谱效果
/// </summary>
public class AudioSpectrumEffect : MonoBehaviour
{
    [SerializeField]
    private AudioSource m_AudioSource;
    [Tooltip("采样通道")]
    [SerializeField]
    [Range(0, 10)]
    private int channel = 0;
    [Tooltip("采样点数量")]
    [SerializeField]
    [Range(64, 8192)]
    //取值范围[64,8192]且必须为2的指数次方
    private int numSamples = 4096;
    private float[] samples;

    [SerializeField]
    private Transform m_Container;
    [SerializeField]
    private Slider m_SliderTemplet;
    [SerializeField]
    private int m_SliderCount = 32;
    [SerializeField]
    private float m_Multiply = 15;//倍乘因子
    [SerializeField]
    private bool m_Loop = true;
    private List<Slider> sliders = new List<Slider>();


    private void Awake()
    {
        samples = new float[numSamples];
        m_AudioSource.loop = m_Loop;
        m_AudioSource.Play();

        if (m_AudioSource.clip != null && channel >= m_AudioSource.clip.channels)
            channel = m_AudioSource.clip.channels - 1;

        CreateSliders();
    }

    private void Update()
    {
        GetSpectrumData();
        UpdateSliders();
    }

    private void GetSpectrumData()
    {
        m_AudioSource.GetSpectrumData(samples, channel, FFTWindow.BlackmanHarris);
    }

    private void CreateSliders()
    {
        for (int i=0; i < m_SliderCount; i++)
        {
            Slider slider = Instantiate<Slider>(m_SliderTemplet);
            slider.gameObject.name = "Slider_"+i.ToString("D2");
            slider.transform.SetParent(m_Container);
            sliders.Add(slider);
        }
        m_SliderTemplet.gameObject.SetActive(false);
    }

    private void UpdateSliders()
    {
        for (int i = 0; i < m_SliderCount; i++)
        {
            Slider slider = sliders[i];
            slider.value = samples[i] * m_Multiply;
        }
    }
}


运行效果

3335.gif

评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容