【Unity游戏】 获取音量大小 完成简易版“不要停!八分音符酱”

    技术2023-06-12  99

    【Unity游戏】 获取音量大小 完成简易版 不要停!八分音符酱

    配置:Unity 2019.2.11f1 + vs2019

    开始操作:

    1. 新建个 2D 项目(2D,3D都行)

    2. 在视图里面右键新建一个 2D 的 sprite 做要操作的对象,一个 3D 的 cube 做地面(因为懒)

    ​ 滴滴滴:

    记得把 3D 的 cube 的碰撞组件换成 2D 的额

    sprite 里面添加 2D 刚体和 2D 碰撞组件

    3. 接下来就来编写少的可怜的代码,不想动脑子,去百度百度,cv大法完成

    新建一个 C# Script

    敲好代码

    using System.Collections; using System.Collections.Generic; using UnityEngine; public class jump : MonoBehaviour { private Rigidbody2D m_rg; public float MoveSpeed; private float JumpSpeed; /// 录制声音 private float volume; private static int VOLUME_DATA_LENGTH = 128; //录制的声音长度 private AudioClip mMicrophoneRecode; //录制的音频 private string mDeviceName; //设备名称 private bool isHaveDevice; private const int frequency = 44100; //码率 private const int lengthSec = 999; //录制时长 // Start is called before the first frame update void Start() { m_rg = gameObject.GetComponent<Rigidbody2D>(); // 初始化音频获取参数 string[] devices = Microphone.devices; // 检查是否连入 mic if (devices.Length > 0) { isHaveDevice = true; //获取设备名称 mDeviceName = devices[0]; //录制一段音频 mMicrophoneRecode = Microphone.Start(mDeviceName, true, lengthSec, frequency); } else { isHaveDevice = false; Debug.Log("no mic"); } } // Update is called once per frame void Update() { //------------------Input.GetAxisRaw没有小数值,只有整数,不会产生缓动------------------ //角色水平移动 //按住D键,判断如果大于0,则向右开始移动 if (Input.GetAxisRaw("Horizontal") > 0) { m_rg.velocity = new Vector2(MoveSpeed, m_rg.velocity.y); //设置自身缩放的值 transform.localScale = new Vector2(0.1f, 0.1f); } //角色水平移动 //按住A键,判断如果小于0,则向左开始移动 else if (Input.GetAxisRaw("Horizontal") < 0) { m_rg.velocity = new Vector2(-MoveSpeed, m_rg.velocity.y); //如果new Vector2(-1f, 1f) x值为负数,则图片进行反转显示 transform.localScale = new Vector2(-0.1f, 0.1f); } else //角色水平移动 //松开按键,判断如果等于0,则停止移动 { m_rg.velocity = new Vector2(0, m_rg.velocity.y); } //角色按下空格键实现跳跃 //禁止二连跳 //要先判断角色是否在地面上,在地面上可以跳,不在地面上则不能跳 JumpSpeed = GetMaxVolume() * 100; if (JumpSpeed > 1) { m_rg.velocity = new Vector2(m_rg.velocity.x, JumpSpeed); } // 检查 sprite 高度 if (this.gameObject.transform.transform.position.y > 4) { this.gameObject.transform.transform.position = new Vector2(this.gameObject.transform.transform.position.x, 4); } } float GetMaxVolume() { float maxVolume = 0f; if (isHaveDevice) { //用于储存一段时间内的音频信息 float[] volumeData = new float[VOLUME_DATA_LENGTH]; //获取录制的音频的开头位置 int offset = Microphone.GetPosition(mDeviceName) - 128 + 1; if (offset < 0) { return 0; } //获取数据 mMicrophoneRecode.GetData(volumeData, offset); //解析数据 for (int i = 0; i < VOLUME_DATA_LENGTH; i++) { if (volumeData[i] > maxVolume) { maxVolume = volumeData[i]; } } } return maxVolume; } } 把 jump 脚本拖拽到 sprite 内(添加 jump 组件) 记得 jump 脚本里面的参数设置下

    好了,简易版的 不要停!八分音符酱 就完成啦啦啦啦啦

    然后,就开始自己的 DIY 吧

    参考:

    在Unity中获取音量大小 https://www.cnblogs.com/Fasty/p/11171168.html控制人物移动 https://www.cnblogs.com/yueqingli/p/10120607.html
    Processed: 0.030, SQL: 9