栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > Unity3D

Unity音频生成波浪线

Unity3D 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Unity音频生成波浪线

传入一个音频生成波浪线效果如下图:

 

using UnityEngine;
using UnityEngine.UI;

public class Test : MonoBehaviour
{
    public AudioClip audioClip;

    public RawImage _rawImage; 
    // Start is called before the first frame update
    void Start()
    {
        _rawImage.texture = BakeAudioWaveform(audioClip);
    }

// 传入一个AudioClip 会将AudioClip上挂载的音频文件生成频谱到一张Texture2D上
public static Texture2D BakeAudioWaveform(AudioClip _clip) {
        int resolution = 20;	// 控制生成波浪线的高度
        int width = 1920;		// 这个是最后生成的Texture2D图片的宽度
        int height = 200;		// 这个是最后生成的Texture2D图片的高度

        resolution = _clip.frequency / resolution;

        float[] samples = new float[_clip.samples * _clip.channels];
        _clip.GetData(samples, 0);

        float[] waveForm = new float[(samples.Length / resolution)];

        float min = 0;
        float max = 0;
        bool inited = false;

        for (int i = 0; i < waveForm.Length; i++) {
            waveForm[i] = 0;

            for (int j = 0; j < resolution; j++) {
                waveForm[i] += Mathf.Abs(samples[(i * resolution) + j]);
            }

            if (!inited) {
                min = waveForm[i];
                max = waveForm[i];
                inited = true;
            } else {
                if (waveForm[i] < min) {
                    min = waveForm[i];
                }

                if (waveForm[i] > max) {
                    max = waveForm[i];
                }
            }
            //waveForm[i] /= resolution;
        }


        Color backgroundColor = Color.black;
        Color waveformColor = Color.green;
        Color[] blank = new Color[width * height];
        Texture2D texture = new Texture2D(width, height);

        for (int i = 0; i < blank.Length; ++i) {
            blank[i] = backgroundColor;
        }

        texture.SetPixels(blank, 0);

        float xScale = (float)width / (float)waveForm.Length;

        int tMid = (int)(height / 2.0f);
        float yScale = 1;

        if (max > tMid) {
            yScale = tMid / max;
        }

        for (int i = 0; i < waveForm.Length; ++i) {
            int x = (int)(i * xScale);
            int yOffset = (int)(waveForm[i] * yScale);
            int startY = tMid - yOffset;
            int endY = tMid + yOffset;

            for (int y = startY; y <= endY; ++y) {
                texture.SetPixel(x, y, waveformColor);
            }
        }

        texture.Apply();
        return texture;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/900171.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号