-
Notifications
You must be signed in to change notification settings - Fork 6
/
UnityAudioSource.cs
93 lines (79 loc) · 2.73 KB
/
UnityAudioSource.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#nullable enable
using System;
using UniRx;
namespace Mochineko.VoiceActivityDetection
{
/// <summary>
/// A voice source that uses UnityEngine.AudioSource via OnAudioFilterRead().
/// </summary>
public sealed class UnityAudioSource : IVoiceSource
{
private readonly int readBufferSize;
private readonly bool mute;
private readonly int samplingRate;
private int channels = 1;
private bool isActive = true;
private readonly Subject<VoiceSegment> onSegmentRead = new();
IObservable<VoiceSegment> IVoiceSource.OnSegmentRead => onSegmentRead;
/// <summary>
/// Creates a new instance of <see cref="UnityAudioSource"/>.
/// </summary>
/// <param name="readBufferSize">Fixed buffer size to read voice data at once.</param>
/// <param name="mute">Mute output audio or not.</param>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public UnityAudioSource(
int readBufferSize = 4096,
bool mute = false)
{
if (readBufferSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(readBufferSize), readBufferSize, "Read buffer size must be greater than 0.");
}
this.readBufferSize = readBufferSize;
this.mute = mute;
this.samplingRate = UnityEngine.AudioSettings.outputSampleRate;
}
void IDisposable.Dispose()
{
onSegmentRead.Dispose();
}
int IVoiceSource.SamplingRate
=> this.samplingRate;
int IVoiceSource.Channels
=> this.channels;
void IVoiceSource.Update()
{
// Do nothing
}
void IVoiceSource.SetSourceActive(bool isActive)
{
this.isActive = isActive;
}
/// <summary>
/// Redirects OnAudioFilterRead() to OnSegmentRead.
/// </summary>
/// <param name="data"></param>
/// <param name="channels"></param>
public void OnAudioFilterRead(float[] data, int channels)
{
if (!isActive)
{
return;
}
this.channels = channels;
// Read data with buffer
var position = 0;
while (position < data.Length)
{
var readLength = Math.Min(readBufferSize, data.Length - position);
var span = data.AsSpan(position, readLength);
onSegmentRead.OnNext(new VoiceSegment(span, samplingRate, channels));
position += readLength;
}
if (mute)
{
Array.Clear(data, 0, data.Length);
}
}
}
}