From b049b4f88dad22bd6bc774a55c583294441baa1a Mon Sep 17 00:00:00 2001
From: Nicky McDonald <43690021+nickyMcDonald@users.noreply.github.com>
Date: Sat, 24 Feb 2024 03:44:13 -0500
Subject: [PATCH] AttachAudioMixedProcessor Utils for easy callback (#215)
---
Raylib-cs/types/AudioCallback.cs | 10 ++++++++++
Raylib-cs/types/AudioMixed.cs | 23 +++++++++++++++++++++++
Raylib-cs/types/Raylib.Utils.cs | 24 ++++++++++++++++++++++++
3 files changed, 57 insertions(+)
create mode 100644 Raylib-cs/types/AudioCallback.cs
create mode 100644 Raylib-cs/types/AudioMixed.cs
diff --git a/Raylib-cs/types/AudioCallback.cs b/Raylib-cs/types/AudioCallback.cs
new file mode 100644
index 0000000..2f7b372
--- /dev/null
+++ b/Raylib-cs/types/AudioCallback.cs
@@ -0,0 +1,10 @@
+using System;
+
+namespace Raylib_cs;
+
+///
+/// Audio stream processor.
+/// Used with Raylib.AttachAudioMixedProcessor()
+/// and Raylib.DetachAudioMixedProcessor()
+///
+public delegate void AudioCallback(Span buffer);
diff --git a/Raylib-cs/types/AudioMixed.cs b/Raylib-cs/types/AudioMixed.cs
new file mode 100644
index 0000000..bf98491
--- /dev/null
+++ b/Raylib-cs/types/AudioMixed.cs
@@ -0,0 +1,23 @@
+using System;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+namespace Raylib_cs;
+
+internal static unsafe class AudioMixed
+{
+ public static AudioCallback Callback = null;
+
+ [UnmanagedCallersOnly(CallConvs = new[]
+ {
+ typeof(CallConvCdecl),
+ })]
+ public static void Processor(void* buffer, uint frames)
+ {
+ // The buffer is stereo audio, so we need to double our frame count.
+ frames = Math.Min(frames * 2, int.MaxValue);
+
+ Span floats = new(buffer, (int)frames);
+ Callback?.Invoke(floats);
+ }
+}
diff --git a/Raylib-cs/types/Raylib.Utils.cs b/Raylib-cs/types/Raylib.Utils.cs
index c3b2f1d..46ba915 100644
--- a/Raylib-cs/types/Raylib.Utils.cs
+++ b/Raylib-cs/types/Raylib.Utils.cs
@@ -1261,6 +1261,30 @@ public static unsafe partial class Raylib
}
}
+ ///
+ /// Attach audio stream processor to the entire audio pipeline
+ ///
+ public static void AttachAudioMixedProcessor(AudioCallback processor)
+ {
+ if (AudioMixed.Callback == null)
+ {
+ AudioMixed.Callback = processor;
+ AttachAudioMixedProcessor(&AudioMixed.Processor);
+ }
+ }
+
+ ///
+ /// Detach audio stream processor from the entire audio pipeline
+ ///
+ public static void DetachAudioMixedProcessor(AudioCallback processor)
+ {
+ if (AudioMixed.Callback == processor)
+ {
+ DetachAudioMixedProcessor(&AudioMixed.Processor);
+ AudioMixed.Callback = null;
+ }
+ }
+
public static string SubText(this string input, int position, int length)
{
return input.Substring(position, Math.Min(length, input.Length));