Skip to content
Merged
25 changes: 25 additions & 0 deletions src/Discord.Net.WebSocket/Audio/Streams/OpusEncodeStream.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;

Expand All @@ -23,6 +24,30 @@ public OpusEncodeStream(AudioStream next, int bitrate, AudioApplication applicat
_buffer = new byte[OpusConverter.FrameBytes];
}

/// <summary>
/// Sends silent frames to avoid interpolation errors after breaks in data transmission.
/// </summary>
/// <returns></returns>
public async Task WriteSilentFramesAsync()
{
// https://discord.com/developers/docs/topics/voice-connections#voice-data-interpolation

byte[] frameBytes = new byte[OpusConverter.FrameBytes];

// Magic silence numbers.
frameBytes[0] = 0xF8;
frameBytes[1] = 0xFF;
frameBytes[2] = 0xFE;

// The rest of the array is already zeroes, so no need to fill the rest.

const int frameCount = 5;
for (int i = 0; i < frameCount; i += 1)
{
await WriteAsync(frameBytes, 0, frameBytes.Length);
}
}

public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancelToken)
{
//Assume thread-safe
Expand Down