Unity3D中把AudioClip保存为Wav文件
时间: 2023-07-16 19:16:53 浏览: 330
在Unity3D中,可以使用以下代码将AudioClip保存为Wav文件:
```c#
using UnityEngine;
using System.IO;
public static void SaveAudioClipToWav(AudioClip clip, string filepath)
{
var data = ConvertAudioClipToByteArray(clip);
var fileStream = new FileStream(filepath, FileMode.Create);
var binaryWriter = new BinaryWriter(fileStream);
binaryWriter.Write(data);
fileStream.Close();
}
private static byte[] ConvertAudioClipToByteArray(AudioClip clip)
{
var samples = new float[clip.samples];
clip.GetData(samples, 0);
var byteArray = new byte[samples.Length * 2];
var rescaleFactor = 32767;
for (var i = 0; i < samples.Length; i++)
{
var intData = (short)(samples[i] * rescaleFactor);
var byteArr = new byte[2];
byteArr = System.BitConverter.GetBytes(intData);
byteArray[i * 2] = byteArr[0];
byteArray[(i * 2) + 1] = byteArr[1];
}
return byteArray;
}
```
调用该函数时,需要传入要保存的AudioClip和文件路径。例如:
```c#
SaveAudioClipToWav(myAudioClip, Application.dataPath + "/myAudioFile.wav");
```
这将把名为myAudioClip的AudioClip保存为myAudioFile.wav文件,路径为Unity项目的Assets文件夹下。
阅读全文