Created
March 25, 2019 00:03
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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