Improved BufferedAudioTarget loop
This commit is contained in:
@@ -18,8 +18,7 @@ namespace Discord.Audio
|
|||||||
internal BufferedAudioTarget(DiscordVoiceAPIClient client, int samplesPerFrame, CancellationToken cancelToken)
|
internal BufferedAudioTarget(DiscordVoiceAPIClient client, int samplesPerFrame, CancellationToken cancelToken)
|
||||||
{
|
{
|
||||||
_client = client;
|
_client = client;
|
||||||
double milliseconds = samplesPerFrame / 48.0;
|
long ticksPerFrame = samplesPerFrame / 48;
|
||||||
double ticksPerFrame = Stopwatch.Frequency / 1000.0 * milliseconds;
|
|
||||||
|
|
||||||
_cancelTokenSource = new CancellationTokenSource();
|
_cancelTokenSource = new CancellationTokenSource();
|
||||||
cancelToken = CancellationTokenSource.CreateLinkedTokenSource(_cancelTokenSource.Token, cancelToken).Token;
|
cancelToken = CancellationTokenSource.CreateLinkedTokenSource(_cancelTokenSource.Token, cancelToken).Token;
|
||||||
@@ -28,31 +27,26 @@ namespace Discord.Audio
|
|||||||
_task = Run(ticksPerFrame, cancelToken);
|
_task = Run(ticksPerFrame, cancelToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Task Run(double ticksPerFrame, CancellationToken cancelToken)
|
private Task Run(long ticksPerFrame, CancellationToken cancelToken)
|
||||||
{
|
{
|
||||||
return Task.Run(async () =>
|
return Task.Run(async () =>
|
||||||
{
|
{
|
||||||
var stopwatch = Stopwatch.StartNew();
|
long nextTick = Environment.TickCount;
|
||||||
long lastTick = stopwatch.ElapsedTicks;
|
|
||||||
double ticksPerMilli = Stopwatch.Frequency / 1000.0;
|
|
||||||
while (!cancelToken.IsCancellationRequested)
|
while (!cancelToken.IsCancellationRequested)
|
||||||
{
|
{
|
||||||
long thisTick = stopwatch.ElapsedTicks;
|
long tick = Environment.TickCount;
|
||||||
double remaining = ticksPerFrame - (thisTick - lastTick);
|
long dist = nextTick - tick;
|
||||||
if (remaining <= 0)
|
if (dist <= 0)
|
||||||
{
|
{
|
||||||
byte[] buffer;
|
byte[] buffer;
|
||||||
if (_queue.TryDequeue(out buffer))
|
if (_queue.TryDequeue(out buffer))
|
||||||
await _client.SendAsync(buffer, buffer.Length).ConfigureAwait(false);
|
await _client.SendAsync(buffer, buffer.Length).ConfigureAwait(false);
|
||||||
else
|
else
|
||||||
await _client.SendAsync(_silencePacket, _silencePacket.Length).ConfigureAwait(false);
|
await _client.SendAsync(_silencePacket, _silencePacket.Length).ConfigureAwait(false);
|
||||||
lastTick = thisTick;
|
nextTick += ticksPerFrame;
|
||||||
}
|
|
||||||
else if (remaining > 1)
|
|
||||||
{
|
|
||||||
int millis = (int)Math.Floor(remaining / ticksPerMilli);
|
|
||||||
await Task.Delay(millis).ConfigureAwait(false);
|
|
||||||
}
|
}
|
||||||
|
else if (dist > 1)
|
||||||
|
await Task.Delay((int)dist).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user