|
| 1 | +using System.Threading.Channels; |
| 2 | + |
| 3 | +using NetCord.Gateway.Voice; |
| 4 | + |
| 5 | +namespace MyBot; |
| 6 | + |
| 7 | +internal static class Examples |
| 8 | +{ |
| 9 | + public static void VoiceReceiveEvent(VoiceClient voiceClient) |
| 10 | + { |
| 11 | + voiceClient.VoiceReceive += args => |
| 12 | + { |
| 13 | + if (voiceClient.Cache.SsrcUsers.TryGetValue(args.Ssrc, out var userId)) |
| 14 | + Console.WriteLine($"Received audio from user {userId}"); |
| 15 | + else |
| 16 | + Console.WriteLine($"Received audio from unknown user with SSRC {args.Ssrc}"); |
| 17 | + |
| 18 | + return default; |
| 19 | + }; |
| 20 | + } |
| 21 | + |
| 22 | + public static void VoiceReceiveEventAsyncHandler(VoiceClient voiceClient) |
| 23 | + { |
| 24 | + voiceClient.VoiceReceive += args => |
| 25 | + { |
| 26 | + // You may consider renting a buffer |
| 27 | + // from 'ArrayPool<T>' in a real application |
| 28 | + var ownedFrame = args.Frame.ToArray(); |
| 29 | + |
| 30 | + return HandleAsync(ownedFrame, args.Ssrc); |
| 31 | + |
| 32 | + static async ValueTask HandleAsync(byte[] frame, uint ssrc) |
| 33 | + { |
| 34 | + await Task.Delay(100); // Simulate async processing |
| 35 | + |
| 36 | + Console.WriteLine($"Processed audio frame from SSRC {ssrc}"); |
| 37 | + } |
| 38 | + }; |
| 39 | + } |
| 40 | + |
| 41 | + public static async Task BufferingReceivedAudio(VoiceClient voiceClient) |
| 42 | + { |
| 43 | + // Configure the channel to drop frames when the buffer is full; |
| 44 | + // 1000 frames means from 2.5 to 120 seconds of |
| 45 | + // audio depending on the Opus frame duration; |
| 46 | + // Dropping frames should generally never happen, but it is a good |
| 47 | + // idea to handle it just in case to avoid running out of memory |
| 48 | + var channel = Channel.CreateBounded<(byte[] Frame, uint? Timestamp)>(new BoundedChannelOptions(1000) |
| 49 | + { |
| 50 | + FullMode = BoundedChannelFullMode.DropWrite, |
| 51 | + }); |
| 52 | + |
| 53 | + var writer = channel.Writer; |
| 54 | + |
| 55 | + voiceClient.VoiceReceive += args => |
| 56 | + { |
| 57 | + // You may consider renting a buffer from 'ArrayPool<T>' in a real application |
| 58 | + var frame = args.Frame.ToArray(); |
| 59 | + |
| 60 | + return writer.WriteAsync((frame, args.Timestamp)); |
| 61 | + }; |
| 62 | + |
| 63 | + await foreach (var (frame, timestamp) in channel.Reader.ReadAllAsync()) |
| 64 | + Console.WriteLine($"Received audio frame of size {frame.Length} with timestamp {timestamp}"); |
| 65 | + } |
| 66 | + |
| 67 | + public static void CreateOpusDecodeStream(Stream stream) |
| 68 | + { |
| 69 | + OpusDecodeStream opusDecodeStream = new(stream, |
| 70 | + PcmFormat.Float, |
| 71 | + VoiceChannels.Stereo); |
| 72 | + } |
| 73 | +} |
0 commit comments