資源簡介
這是一個使用C#編寫的Unity腳本,可以錄制麥克風的語音輸入,保存成WAV格式的文件。使用說明:首先要有麥克風接入,調成默認輸入設備,然后把腳本放在任意一個物體上,接口可以不用配置,都有默認值,運行時點擊G是開始錄音,H是播放錄音,J是保存文件。
代碼片段和文件信息
using?System.Collections;
using?System.Collections.Generic;
using?UnityEngine;
using?System.IO;
using?System;
public?class?RecordMic?:?MonoBehaviour?{
public?string?filePath?=?null;
public?int?Recordlength?=?30;
//?Use?this?for?initialization
void?Start?()?{
if?(String.IsNullOrEmpty(filePath))
filePath?=?Application.dataPath?+?“/record.wav“;
}
//?Update?is?called?once?per?frame
void?Update?()?{
if?(Input.GetKeyDown?(KeyCode.G))
Recording?();
else?if?(Input.GetKeyDown?(KeyCode.H))
PlayRecord?();
else?if?(Input.GetKeyDown?(KeyCode.J))
SaveRecord();
}
[HideInInspector]
public?AudioClip?clip;
//錄音的采樣率
const?int?samplingRate?=?44100;
///?
///?開始錄音
///?
public?void?Recording()
{
string[]?micDevices?=?Microphone.devices;
if?(micDevices.Length?==?0)
{
Debug.Log(“沒有找到錄音組件“);
return;
}
Debug.Log(“錄音時長為“+Recordlength.ToString()+“?秒“);
Microphone.End(null);//錄音前先停掉錄音,錄音參數為null時采用的是默認的錄音驅動
clip?=?Microphone.Start(null?false?Recordlength?samplingRate);
}
///?
///?停止錄音
///?
public?void?StopRecord()
{
int?audioLength;
int?lastPos?=?Microphone.GetPosition(null);
if?(Microphone.IsRecording(null))
{
audioLength?=?lastPos?/?samplingRate;
}
else
{
audioLength?=?Recordlength;
}
Microphone.End(null);
if?(audioLength?1.0f)
{
Debug.Log(“錄音時長短“);
}
}
///?
///?播放錄音
///?
public?void?PlayRecord()
{
StopRecord();
AudioSource.PlayClipAtPoint(clip?Vector3.zero);
}
///?
///?保存錄音
///?
public?void?SaveRecord()
{
StopRecord();
try
{
Save(clip?filePath);
Debug.Log(“保存完畢“);
}
catch?(Exception?ex)
{
Debug.Log(ex.Message?+?ex.StackTrace);
}
}
public?static?void?Save(AudioClip?clip?string?path)
{
string?filePath?=?Path.GetDirectoryName(path);
if?(!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
using?(FileStream?fileStream?=?CreateEmpty(path))
{
ConvertAndWrite(fileStream?clip);
WriteHeader(fileStream?clip);
}
}
private?static?void?ConvertAndWrite(FileStream?fileStream?AudioClip?clip)
{
float[]?samples?=?new?float[clip.samples];
clip.GetData(samples?0);
評論
共有 條評論