简单的把脚本加到摄像机上就行
下面是我写的脚本,有个问题 因为是自动调用检测的 调用录音unity调用有延时 会出现一些延时小问题,可以参考我的代码 改改 做个通过按钮点击录音结束播放录音还是能实现的
using System.Collections.Generic;
using UnityEngine;
using System.Collections;
public class Tom2 : MonoBehaviour
{
//public float power = 1;
//public float min = 0;
// public AudioClip audioClip = null;//AudioClip音频剪辑
//public AudioSource audioSource;//AudioSource 音频源
public bool audioclipWorking = false;
public string audioIsPlaying;
public bool microphoneWorking = false;
private List<float> samplesList; //播放数据存储
public float samplesMaxValue;
public int ClipLength;
private void Start()
{
samplesList = new List<float>(); //不固定
startRecord();
}
private void Update()
{
audioIsPlaying = audio.isPlaying.ToString();
Screen.sleepTimeout = SleepTimeout.NeverSleep;
if (microphoneWorking)
{
if (!Microphone.IsRecording(null))
{
microphoneWorking = false;
JudgeRecord();
}
}
if (audioclipWorking)
{
if (audio.isPlaying == false)
{
samplesList.Clear();
startRecord();
audioclipWorking = false;
}
}
}
private void startRecord()
{
audio.clip = Microphone.Start(null, false, 1, 44100);
while (Microphone.GetPosition(null) <= 0) ;
microphoneWorking = true;
}
public void JudgeRecord()
{
float max = 0;
float[] tempSamples; //临时数据存储
tempSamples = new float[audio.clip.samples * audio.clip.channels];
audio.clip.GetData(tempSamples, 0);
foreach (float s in tempSamples)
{
float m = Mathf.Abs(s);
if (max < m)
{
max = m; //刚刚录制音频数据的取最大值
}
}
samplesMaxValue = max;
if (max > 0.1)
{
//判断有人说话
startRecord();
foreach (float e in tempSamples)
{
samplesList.Add(e);//保存数据
}
//再录下一秒
}
else
{
//无人说话
if (audio.clip != null && samplesList != null)
{
if (samplesList.Count > 1000)
{
AudioClip myClip = AudioClip.Create("tom", samplesList.Count, 1, 44100, false, false);
myClip.SetData(samplesList.ToArray(), 0);
audio.clip = myClip;
audio.loop = false;
audio.pitch = 1.2f;
audio.Play();
audioclipWorking = true;
}
else
{
startRecord();
}
}
else
{
startRecord();
}
}
}
private void OnGUI()
{
GUI.Label(new Rect(60, 30 * 1, Screen.width, 20), "samplesMaxValue:" + samplesMaxValue);
GUI.Label(new Rect(60, 30 * 2, Screen.width, 20), "ClipLength:" + ClipLength);
GUI.Label(new Rect(60, 30 * 3, Screen.width, 20), "audioIsPlaying:" + audioIsPlaying);
GUI.Label(new Rect(60, 30 * 4, Screen.width, 20), "audioclipWorking:" + audioclipWorking);
GUI.Label(new Rect(60, 30 * 5, Screen.width, 20), "microphoneWorking:" + microphoneWorking);
GUI.Label(new Rect(60, 30 * 6, Screen.width, 20), "audio.clip.samples:" + audio.clip.samples);
GUI.Label(new Rect(60, 30 * 7, Screen.width, 20), "audio.clip.length:" + audio.clip.length);
GUI.Label(new Rect(60, 30 * 8, Screen.width, 20), "audio.clip.channels:" + audio.clip.channels);
GUI.Label(new Rect(60, 30 * 8, Screen.width, 20), "Microphone.GetPosition:" + Microphone.GetPosition(null));
}
}原文地址:http://blog.csdn.net/chh19941125/article/details/45935013