-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLocalAudioSink.cs
109 lines (84 loc) · 3.38 KB
/
LocalAudioSink.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
using System.Collections.Concurrent;
using NAudio.Wave;
using OmniBot.Common.Audio;
namespace OmniBot.Windows
{
public class LocalAudioSink : IAudioSink
{
private class WaveProviderWrapper : IWaveProvider
{
public WaveFormat WaveFormat => audioSource?.Format.ToWaveFormat();
private IAudioSource audioSource;
private ConcurrentQueue<byte[]> bufferQueue = new();
private byte[] currentBuffer = null;
private int currentBufferPosition = 0;
public void ChangeAudioSource(IAudioSource audioSource)
{
if (this.audioSource != null)
this.audioSource.OnAudioBufferReceived -= AudioSource_OnAudioBufferReceived;
this.audioSource = audioSource;
bufferQueue.Clear();
currentBufferPosition = 0;
currentBuffer = null;
if (audioSource != null)
audioSource.OnAudioBufferReceived += AudioSource_OnAudioBufferReceived;
}
public int Read(byte[] buffer, int offset, int count)
{
int n = 0;
while (n < count)
{
if (currentBuffer == null && !bufferQueue.TryDequeue(out currentBuffer))
{
Array.Clear(buffer, offset + n, count - n);
break;
}
if (currentBuffer.Length - currentBufferPosition > count - n)
{
Array.Copy(currentBuffer, currentBufferPosition, buffer, offset + n, count - n);
currentBufferPosition += count - n;
break;
}
Array.Copy(currentBuffer, currentBufferPosition, buffer, offset + n, currentBuffer.Length - currentBufferPosition);
n += currentBuffer.Length - currentBufferPosition;
currentBufferPosition = 0;
currentBuffer = null;
}
return count;
}
private void AudioSource_OnAudioBufferReceived(AudioBuffer audioBuffer)
{
bufferQueue.Enqueue(audioBuffer.Data);
}
}
public AudioFormat Format => waveOutEvent?.OutputWaveFormat.ToAudioFormat() ?? AudioFormat.Default;
private WaveProviderWrapper waveProviderWrapper = new();
private WaveOutEvent waveOutEvent;
public LocalAudioSink()
{
}
public Task PlayAsync(IAudioSource audioSource, CancellationToken cancellationToken = default)
{
if (waveOutEvent != null)
{
waveOutEvent.Stop();
waveOutEvent.Dispose();
}
waveProviderWrapper.ChangeAudioSource(audioSource);
if (audioSource != null)
{
waveOutEvent = new WaveOutEvent();
waveOutEvent.Init(waveProviderWrapper);
waveOutEvent.Play();
if (cancellationToken != default)
{
Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken).ContinueWith(t =>
{
PlayAsync(null);
});
}
}
return Task.CompletedTask;
}
}
}