DenoisedAudio.cs
2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/// Copyright (c) 2025 Xiaomi Corporation (authors: Fangjun Kuang)
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace SherpaOnnx
{
public class DenoisedAudio
{
public DenoisedAudio(IntPtr p)
{
_handle = new HandleRef(this, p);
}
public bool SaveToWaveFile(String filename)
{
Impl impl = (Impl)Marshal.PtrToStructure(Handle, typeof(Impl));
byte[] utf8Filename = Encoding.UTF8.GetBytes(filename);
byte[] utf8FilenameWithNull = new byte[utf8Filename.Length + 1]; // +1 for null terminator
Array.Copy(utf8Filename, utf8FilenameWithNull, utf8Filename.Length);
utf8FilenameWithNull[utf8Filename.Length] = 0; // Null terminator
int status = SherpaOnnxWriteWave(impl.Samples, impl.NumSamples, impl.SampleRate, utf8FilenameWithNull);
return status == 1;
}
~DenoisedAudio()
{
Cleanup();
}
public void Dispose()
{
Cleanup();
// Prevent the object from being placed on the
// finalization queue
System.GC.SuppressFinalize(this);
}
private void Cleanup()
{
SherpaOnnxDestroyDenoisedAudio(Handle);
// Don't permit the handle to be used again.
_handle = new HandleRef(this, IntPtr.Zero);
}
[StructLayout(LayoutKind.Sequential)]
struct Impl
{
public IntPtr Samples;
public int NumSamples;
public int SampleRate;
}
private HandleRef _handle;
public IntPtr Handle => _handle.Handle;
public int NumSamples
{
get
{
Impl impl = (Impl)Marshal.PtrToStructure(Handle, typeof(Impl));
return impl.NumSamples;
}
}
public int SampleRate
{
get
{
Impl impl = (Impl)Marshal.PtrToStructure(Handle, typeof(Impl));
return impl.SampleRate;
}
}
public float[] Samples
{
get
{
Impl impl = (Impl)Marshal.PtrToStructure(Handle, typeof(Impl));
float[] samples = new float[impl.NumSamples];
Marshal.Copy(impl.Samples, samples, 0, impl.NumSamples);
return samples;
}
}
[DllImport(Dll.Filename)]
private static extern void SherpaOnnxDestroyDenoisedAudio(IntPtr handle);
[DllImport(Dll.Filename)]
private static extern int SherpaOnnxWriteWave(IntPtr samples, int n, int sample_rate, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1)] byte[] utf8Filename);
}
}