WAV utility for saving and loading wav files in Unity
WAV utility for recording and audio playback functions in Unity.
public AudioSource audioSource; // hook up with scene's AudioSource in Unity Editor inspector
public void LoadWavFile (string filename)
{
string path = string.Format ("{0}/{1}", Application.persistentDataPath, filename);
AudioClip audioClip = WavUtility.ToAudioClip (path);
audioSource.clip = audioClip;
audioSource.Play ();
}
private AudioClip audioClip;
public int recordTime = 2; // no. of seconds can be set in Unity Editor inspector
private const int sampleRate = 16000; // sample rate for recording speech
public void RecordAudio ()
{
if (Microphone.devices.Length == 0) {
Debug.LogWarning ("No microphone found to record audio clip sample with.");
return;
}
string mic = Microphone.devices [0];
audioClip = Microphone.Start (mic, false, recordTime, sampleRate);
}
public string SaveWavFile ()
{
string filepath;
byte[] bytes = WavUtility.FromAudioClip (audioClip, out filepath, true);
return filepath;
}
By design the ToAudioClip method only supports loading wav files that are stored using Unity's Application data path (Application.persistentDataPath
or Application.dataPath
). In order to load bundled resources it would be better to use Unity's Resources.Load("filename") typeof(AudioClip)
method.
If you need to load WAV files from a remote URL then use the UnityWebRequest.GetAudioClip
method which uses the AudioClip download handler.
public void LoadAudio ()
{
string url = "<WAV_FILE_URL>";
StartCoroutine (LoadAudioURL (url));
}
public IEnumerator LoadAudioURL (string url)
{
UnityWebRequest www = UnityWebRequest.GetAudioClip (url, AudioType.WAV);
yield return www.Send ();
if (www.isError) {
Debug.LogWarning ("Audio error:" + www.error);
} else {
AudioClip audioClip = ((DownloadHandlerAudioClip)www.downloadHandler).audioClip;
audioSource.clip = audioClip;
audioSource.Play ();
}
}
Wav file formatting based on specs detailed in following articles:
Share the <3 @deadlyfingers