using System;
using System.Runtime.InteropServices;
namespace Nerfed.Runtime.Audio;
///
/// Contains raw audio data in a specified Format.
/// Submit this to a SourceVoice to play audio.
///
public class AudioBuffer : AudioResource
{
IntPtr BufferDataPtr;
uint BufferDataLength;
private bool OwnsBufferData;
public Format Format { get; }
///
/// Create a new AudioBuffer.
///
/// If true, the buffer data will be destroyed when this AudioBuffer is destroyed.
public AudioBuffer(
AudioDevice device,
Format format,
IntPtr bufferPtr,
uint bufferLengthInBytes,
bool ownsBufferData) : base(device)
{
Format = format;
BufferDataPtr = bufferPtr;
BufferDataLength = bufferLengthInBytes;
OwnsBufferData = ownsBufferData;
}
///
/// Create another AudioBuffer from this audio buffer.
/// It will not own the buffer data.
///
/// Offset in bytes from the top of the original buffer.
/// Length in bytes of the new buffer.
///
public AudioBuffer Slice(int offset, uint length)
{
return new AudioBuffer(Device, Format, BufferDataPtr + offset, length, false);
}
///
/// Create an FAudioBuffer struct from this AudioBuffer.
///
/// Whether we should set the FAudioBuffer to loop.
public FAudio.FAudioBuffer ToFAudioBuffer(bool loop = false)
{
return new FAudio.FAudioBuffer
{
Flags = FAudio.FAUDIO_END_OF_STREAM,
pContext = IntPtr.Zero,
pAudioData = BufferDataPtr,
AudioBytes = BufferDataLength,
PlayBegin = 0,
PlayLength = 0,
LoopBegin = 0,
LoopLength = 0,
LoopCount = loop ? FAudio.FAUDIO_LOOP_INFINITE : 0
};
}
protected override unsafe void Dispose(bool disposing)
{
if (!IsDisposed)
{
if (OwnsBufferData)
{
NativeMemory.Free((void*) BufferDataPtr);
}
}
base.Dispose(disposing);
}
}