StephennFernandes's picture
CIIL Anuvani-LID
bd48fd1
Raw History Blame Contribute Delete
2.33 kB
// Copyright (c) 2026, CIIL Anuvani-LID. Apache-2.0.
// Binding test (see tests/bindings/python_ref.py): the C# API (.NET MAUI, Unity), against the Linux build of
// libsherpa-onnx-c-api.so.
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using SherpaOnnx;
class Program
{
[StructLayout(LayoutKind.Sequential)]
struct Wave
{
public IntPtr Samples;
public int SampleRate;
public int NumSamples;
}
[DllImport("sherpa-onnx-c-api")]
static extern IntPtr SherpaOnnxReadWave([MarshalAs(UnmanagedType.LPStr)] string filename);
[DllImport("sherpa-onnx-c-api")]
static extern void SherpaOnnxFreeWave(IntPtr wave);
static (float[], int) ReadWave(string path)
{
IntPtr p = SherpaOnnxReadWave(path);
Wave w = Marshal.PtrToStructure<Wave>(p);
float[] samples = new float[w.NumSamples];
Marshal.Copy(w.Samples, samples, 0, w.NumSamples);
SherpaOnnxFreeWave(p);
return (samples, w.SampleRate);
}
static void Main(string[] args)
{
string model = args[0], vad = args[1], longWav = args[2];
var modelConfig = new AudioTaggingModelConfig();
modelConfig.Lid = model;
modelConfig.NumThreads = 2;
var config = new AudioTaggingConfig();
config.Model = modelConfig;
config.TopK = 23;
var tagger = new AudioTagging(config);
foreach (var path in args.Skip(3))
{
var (samples, sampleRate) = ReadWave(path);
var stream = tagger.CreateStream();
stream.AcceptWaveform(sampleRate, samples);
var events = tagger.Compute(stream);
var ev = string.Join(",", events.Select(e => $"[\"{e.Name}\",{e.Index},{e.Prob.ToString("R", System.Globalization.CultureInfo.InvariantCulture)}]"));
Console.WriteLine($"{{\"file\":\"{Path.GetFileName(path)}\",\"events\":[{ev}]}}");
}
var pipelineConfig = new LidPipelineConfig();
pipelineConfig.Model = modelConfig;
pipelineConfig.VadModel = vad;
var pipeline = new LidPipeline(pipelineConfig);
var (s, sr) = ReadWave(longWav);
Console.WriteLine($"{{\"pipeline_file\":\"{Path.GetFileName(longWav)}\",\"pipeline\":{pipeline.Process(s, sr)}}}");
}
}