Unity提供的麦克风API在录制的时候默认只能录制固定时长的音频,为了录制长音频可以使用循环录制的方法。
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class MicUnlimitedDuration : MonoBehaviour { public delegate void AudioRecordHandle(AudioClip audioClip); public AudioSource audioSource; AudioClip micClip; bool isMicRecordFinished= true; List<float> micDataList = new List<float>(); float[] micDataTemp; string micName; public void StartMicrophone() { StopCoroutine(StartMicrophone(null, PlayAudioRecord)); StartCoroutine(StartMicrophone(null, PlayAudioRecord)); } IEnumerator StartMicrophone(string microphoneName,AudioRecordHandle audioRecordFinishedEvent) { Debug.Log("Start Mic"); micDataList = new List<float>(); micName = microphoneName; micClip = Microphone.Start(micName, true,2,16000); isMicRecordFinished = false; int length = micClip.channels * micClip.samples; bool isSaveFirstHalf = true;//将音频从中间分生两段,然后分段保存 int micPosition; while (!isMicRecordFinished) { if (isSaveFirstHalf) { yield return new WaitUntil(() => { micPosition = Microphone.GetPosition(micName);return micPosition > length * 6 / 10 && micPosition < length; });//保存前半段 micDataTemp = new float[length / 2]; micClip.GetData(micDataTemp, 0); micDataList.AddRange(micDataTemp); isSaveFirstHalf = !isSaveFirstHalf; } else { yield return new WaitUntil(() => { micPosition = Microphone.GetPosition(micName); return micPosition > length / 10 && micPosition < length / 2; });//保存后半段 micDataTemp = new float[length/2]; micClip.GetData(micDataTemp, length / 2); micDataList.AddRange(micDataTemp); isSaveFirstHalf = !isSaveFirstHalf; } } micPosition = Microphone.GetPosition(micName); if (micPosition <= length)//前半段 { micDataTemp = new float[micPosition/2]; micClip.GetData(micDataTemp, 0); } else { micDataTemp = new float[micPosition - length/2]; micClip.GetData(micDataTemp, length/2); } micDataList.AddRange(micDataTemp); Microphone.End(micName); AudioClip newAudioClip = AudioClip.Create("RecordClip", micDataList.Count, 1, 16000, false); newAudioClip.SetData(micDataList.ToArray(), 0); audioRecordFinishedEvent(newAudioClip); Debug.Log("RecordEnd"); } public void StopMicrophone() { Debug.Log("Stop mic"); isMicRecordFinished = true; } void PlayAudioRecord(AudioClip newAudioClip) { audioSource.clip = newAudioClip; audioSource.Play(); } }