Skip to content

Instantly share code, notes, and snippets.

@olokobayusuf
Created March 25, 2019 00:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olokobayusuf/c723867d701c73fc99841de61f3e199f to your computer and use it in GitHub Desktop.
Save olokobayusuf/c723867d701c73fc99841de61f3e199f to your computer and use it in GitHub Desktop.
A NatMic audio recorder capable of streaming microphone audio to an AudioClip in realtime.
/*
* NatMic
* Copyright (c) 2019 Yusuf Olokoba
*/
namespace NatMic.Recorders {
using UnityEngine;
using System.Runtime.CompilerServices;
using Docs;
/// <summary>
/// A recorder that doubles as a realtime AudioClip
/// </summary>
public sealed class RealtimeClip : IAudioRecorder {
#region --Client API--
/// <summary>
/// Create a realtime clip
/// </summary>
public RealtimeClip (int sampleRate, int channelCount) {
stream = new AudioStream();
clip = AudioClip.Create("NatMic Realtime Clip", int.MaxValue, channelCount, sampleRate, true, OnAudioDataRead);
}
/// <summary>
/// Destroy the realtime clip
/// </summary>
public void Dispose () {
AudioClip.Destroy(clip);
clip = null;
}
#endregion
#region --Operations--
private AudioClip clip;
private AudioStream stream;
void IAudioProcessor.OnSampleBuffer (float[] sampleBuffer, int sampleRate, int channelCount, long timestamp) {
(stream as IAudioProcessor).OnSampleBuffer(sampleBuffer, sampleRate, channelCount, timestamp);
}
private void OnAudioDataRead (float[] destination) {
if (stream.Length >= destination.Length)
stream.Read(destination);
}
public static implicit operator AudioClip (RealtimeClip clip) {
return clip.clip;
}
public static implicit operator bool (RealtimeClip clip) {
return clip != null;
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment