Librosa Tempo Detection C# + Python

63 Views Asked by At

I need to use python's librosa in C# project. My func :

public string calculateBPMPython(string filePath)
        {
            double bpm = 0;

            try
            {
                Runtime.PythonDLL = @"C:\Program Files\Python311\python311.dll";

                PythonEngine.Initialize();
                using (Py.GIL()) // acquire the Python GIL (Global Interpreter Lock)
                {
                    dynamic librosa = Py.Import("librosa");
                    dynamic beat = Py.Import("librosa.beat");

                    // Load the audio file
                    PyObject[] loadArgs = { new PyString(filePath) };
                    using (var loadKwargs = new PyDict())
                    {
                        loadKwargs["sr"] = new PyInt(22050); // sample rate
                        using (PyObject y_sr = librosa.InvokeMethod("load", loadArgs, loadKwargs))
                        {
                            PyObject y = y_sr[0];
                            PyObject sr = y_sr[1];

                            // Prepare arguments for the tempo function
                            using (var tempoKwargs = new PyDict())
                            {
                                tempoKwargs["sr"] = sr; // pass sample rate as a keyword argument

                                // Call the tempo function
                                PyObject tempo = beat.GetAttr("tempo").Invoke(new PyObject[] { y }, tempoKwargs);
                                bpm = tempo[0].As<double>();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string message = "An error occurred: " + ex.Message;
                return message;
            }
            finally
            {
                PythonEngine.Shutdown();
            }

            return bpm.ToString();
        }

Problem is in line :

PyObject tempo = beat.GetAttr("tempo").Invoke(new PyObject[] { y }, tempoKwargs)

Everytime I use that - there is an error : "Too many postional arguments" can you tell me what I do wrong - how can I do it properly to count BPM?

FIles of the music to count BPM are .mp3 and .wav

So I tried many solving but nothing succeed.

0

There are 0 best solutions below