Created
February 8, 2023 11:07
-
-
Save Const-me/082c8d96eb10b76058c5dd9c68b5bfe1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Runtime.InteropServices; | |
using Whisper; | |
/// <summary>This class demonstrates how to implement iAudioBuffer COM interface in C#, to supply audio samples produced by managed code</summary> | |
/// <remarks>The library requires these samples to be <c>float</c> numbers @ 16 kHz sample rate</remarks> | |
sealed class AudioBuffer: iAudioBuffer | |
{ | |
void IDisposable.Dispose() | |
{ | |
free(); | |
GC.SuppressFinalize( this ); | |
} | |
~AudioBuffer() | |
{ | |
free(); | |
} | |
void free() | |
{ | |
Marshal.FreeCoTaskMem( mono ); | |
mono = IntPtr.Zero; | |
length = capacity = 0; | |
} | |
/// <summary>Allocate buffer of the specified length in unmanaged memory</summary> | |
public void allocate( int len ) | |
{ | |
if( len <= capacity ) | |
{ | |
length = len; | |
return; | |
} | |
Marshal.FreeCoTaskMem( mono ); | |
mono = Marshal.AllocCoTaskMem( len * 4 ); | |
if( mono == IntPtr.Zero ) | |
throw new OutOfMemoryException(); | |
length = capacity = len; | |
} | |
/// <summary>Use this span to write data to the internal buffer</summary> | |
public Span<float> pcmMono | |
{ | |
get | |
{ | |
if( 0 != length ) | |
{ | |
unsafe | |
{ | |
return new Span<float>( (void*)mono, length ); | |
} | |
} | |
return Span<float>.Empty; | |
} | |
} | |
IntPtr mono = IntPtr.Zero; | |
int length = 0; | |
int capacity = 0; | |
public TimeSpan timestamp { get; set; } = TimeSpan.Zero; | |
int iAudioBuffer.countSamples() => length; | |
/// <summary>Provide unmanaged pointer to C++ code</summary> | |
IntPtr iAudioBuffer.getPcmMono() => mono; | |
/// <summary>This class doesn't support stereo PCM, that's why always returns <c>null</c>.</summary> | |
/// <remarks>This means it’s not compatible with diarize feature</remarks> | |
IntPtr iAudioBuffer.getPcmStereo() => IntPtr.Zero; | |
void iAudioBuffer.getTime( out TimeSpan time ) => time = timestamp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment