-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathVcMicAudioInput.cs
More file actions
129 lines (103 loc) · 3.11 KB
/
VcMicAudioInput.cs
File metadata and controls
129 lines (103 loc) · 3.11 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
using System;
using System.Collections;
using System.Linq;
using UnityEngine;
namespace MetaVoiceChat.Input.Mic
{
public class VcMicAudioInput : VcAudioInput
{
public event Action<string> OnActiveDeviceChanged;
public string ActiveDevice => Mic?.ActiveDevice ?? null;
public VcMic Mic { get; private set; } = null;
public bool IsInitialized => Mic != null;
public override void StartLocalPlayer()
{
int samplesPerFrame = metaVc.config.samplesPerFrame;
Mic = new(this, samplesPerFrame);
Mic.OnFrameReady += SendAndFilterFrame;
Mic.OnActiveDeviceChanged += Mic_OnActiveDeviceChanged;
if (Mic.Devices.Length > 0)
{
Mic.StartRecording();
}
StartCoroutine(CoReconnect());
}
private void OnDestroy()
{
if (Mic == null)
{
return;
}
Mic.OnFrameReady -= SendAndFilterFrame;
Mic.OnActiveDeviceChanged -= Mic_OnActiveDeviceChanged;
Mic.Dispose();
Mic = null;
StopAllCoroutines();
}
private IEnumerator CoReconnect()
{
yield return new WaitForSecondsRealtime(1f);
while (Mic != null)
{
while (!ShouldReconnect())
{
yield return null;
}
if (Mic == null)
{
yield break;
}
Mic.StopRecording();
yield return null;
yield return null;
if (Mic == null)
{
yield break;
}
if (Mic.Devices.Length > 0)
{
bool success = Mic.StartRecording();
if (!success)
{
// Wait a long time before trying again to avoid spamming warnings
yield return new WaitForSecondsRealtime(4f);
}
}
else
{
yield return new WaitForSecondsRealtime(1f);
}
yield return null;
yield return null;
}
}
private void Mic_OnActiveDeviceChanged(string device)
{
OnActiveDeviceChanged?.Invoke(device);
}
public void SetSelectedDevice(string device)
{
if (Mic == null)
{
return;
}
Mic.SetSelectedDevice(device);
}
private bool ShouldReconnect()
{
if (Mic == null)
{
return true;
}
if (!Mic.IsRecording || !Mic.Devices.Contains(Mic.ActiveDevice))
{
return true;
}
if (Mic.SelectedDevice != Mic.ActiveDevice && Mic.Devices.Contains(Mic.SelectedDevice))
{
return true;
}
return false;
}
}
}