Unity调用麦克风获取麦克风音量

	[SerializeField]
	public float[] volume;
	public float realVolume;//获取的麦克风音量
	private AudioClip[] micRecord;
	public string[] Devices;
	private void Awake()
	{
		Devices = Microphone.devices;
		if (Devices.Length > 0)
		{
			micRecord = new AudioClip[Devices.Length];
			volume = new float[Devices.Length];
			for (int i = 0; i < Devices.Length; i++)
			{
				if (Microphone.devices[i].IsNormalized())
				{
					micRecord[i] = Microphone.Start(Devices[i], true, 999, 44100);
				}
			}
		}
		else
		{
			Debug.LogError("找不到麦克风");
		}
	}
	void Update()
	{
		if (Devices.Length > 0)
		{
			for (int i = 0; i < Devices.Length; i++)
			{
				volume[i] = GetMaxVolume(i);
				if (volume[i] != 0)
				{
					realVolume = volume[i];
				}
			}
		}
}

//每一振处理那一帧接收的音频文件
	float GetMaxVolume(int x)
	{
		float maxVolume = 0f;
		//剪切音频
		float[] volumeData = new float[128];
		int offset = Microphone.GetPosition(Devices[x]) - 128 + 1;
		if (offset < 0)
		{
			return 0;
		}
		micRecord[x].GetData(volumeData, offset);

		for (int i = 0; i < 128; i++)
		{
			float tempMax = volumeData[i];//修改音量的敏感值
			if (maxVolume < tempMax)
			{
				maxVolume = tempMax;
			}
		}
		return maxVolume;
	}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值