-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathBasicAudioSource.cs
More file actions
72 lines (59 loc) · 2.04 KB
/
Copy pathBasicAudioSource.cs
File metadata and controls
72 lines (59 loc) · 2.04 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
using System;
using UnityEngine;
namespace LiveKit
{
/// <summary>
/// An audio source which captures from a Unity <see cref="AudioSource"/> in the scene.
/// </summary>
sealed public class BasicAudioSource : RtcAudioSource
{
private readonly AudioSource _source;
public override event Action<float[], int, int> AudioRead;
private bool _disposed = false;
private bool _started = false;
/// <summary>
/// Creates a new basic audio source for the given <see cref="AudioSource"/> in the scene.
/// </summary>
/// <param name="source">The <see cref="AudioSource"/> to capture from.</param>
/// <param name="sourceType">The type of audio source.</param>
/// <remarks>
/// The sample rate and channel count are taken from Unity's audio configuration.
/// </remarks>
public BasicAudioSource(AudioSource source, RtcAudioSourceType sourceType = RtcAudioSourceType.AudioSourceCustom) : base(sourceType)
{
_source = source;
}
private void OnAudioRead(float[] data, int channels, int sampleRate)
{
AudioRead?.Invoke(data, channels, sampleRate);
}
public override void Start()
{
base.Start();
if (_started) return;
var probe = _source.gameObject.AddComponent<AudioProbe>();
probe.AudioRead += OnAudioRead;
_source.Play();
_started = true;
}
public override void Stop()
{
base.Stop();
if (!_started) return;
var probe = _source.gameObject.GetComponent<AudioProbe>();
UnityEngine.Object.Destroy(probe);
_source.Stop();
_started = false;
}
protected override void Dispose(bool disposing)
{
if (!_disposed && disposing) Stop();
_disposed = true;
base.Dispose(disposing);
}
~BasicAudioSource()
{
Dispose(false);
}
}
}