-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStreamClip.cs
73 lines (58 loc) · 1.87 KB
/
StreamClip.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using UnityEngine;
namespace NuclearVOIP
{
[RequireComponent(typeof(AudioSource))]
internal class StreamClip: MonoBehaviour, InStream<float>
{
private readonly SampleStream buffer = new(48000);
private const int bufferSamples = (int)((48000 * 0.02) * 3); // 3, 20ms packets at 48khz
public event Action? OnReady;
public event Action? OnDry;
private void Awake()
{
enabled = false;
}
public void Write(float sample) // Very inefficient, don't use this
{
Write([sample]);
}
public void Write(float[] samples)
{
buffer.Write(samples);
if (buffer.Count() > bufferSamples && !enabled)
{
enabled = true;
OnReady?.Invoke();
}
}
// Runs on a different thread, suddenly really happy I made the Streams threadsafe.
private void OnAudioFilterRead(float[] data, int channels)
{
int perChannel = data.Length / channels;
int count = buffer.Count();
if (count < perChannel)
{
Plugin.Logger.LogDebug("StreamClip Dry");
enabled = false;
OnDry?.Invoke();
if (count == 0)
return;
}
float[]? samples = buffer.Read(Math.Min(perChannel, count));
if (samples == null)
{
Plugin.Logger.LogDebug("StreamClip Dry");
enabled = false;
OnDry?.Invoke();
return;
}
for (int i = 0; i < samples.Length; i++)
{
int offset = i * channels;
for (int j = 0; j < channels; j++)
data[offset + j] += samples[i];
}
}
}
}