feliwir / SharpAudio

Audio playback/capturing engine for C#
MIT License
176 stars 19 forks source link

MacOS: System.NullReferenceException with the official sample from README.md #43

Closed sandreas closed 2 years ago

sandreas commented 2 years ago

Hello,

I just wanted to try out the library on MacOS with the sample Code from the Readme:

            var engine = AudioEngine.CreateDefault();
            var buffer = engine.CreateBuffer();
            var source = engine.CreateSource();

            // Play a 1s long sound at 440hz
            AudioFormat format;
            format.BitsPerSample = 16;
            format.Channels = 1;
            format.SampleRate = 44100;
            float freq = 440.0f;
            var size = format.SampleRate;
            var samples = new short[size];

            for (int i = 0; i < size; i++)
            {
                samples[i] = (short)(32760 * Math.Sin((2 * Math.PI * freq) / size * i));
            }

            buffer.BufferData(samples, format);

            source.QueueBuffer(buffer);

            source.Play();

It failed with and unhandled exception:

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
   at App.Run() in App.cs:line 105
   at Program.<Main>$(String[] args) in Program.cs:line 13

The line, that fails, is:

            var buffer = engine.CreateBuffer();

Environment:

What am I doing wrong?

feliwir commented 2 years ago

Hello, we currently don’t support an native AudioBackend on macOS. You could try using OpenAL and see if it picks that up: https://github.com/feliwir/SharpAudio/blob/master/src/SharpAudio.ALBinding/AlNative.cs#L31

Either of these dylibs has to be available

sandreas commented 2 years ago

Awesome, that worked - thank you. Short "howto" (not the best or most elegant way, but it works):

brew install openal-soft
brew list openal-soft

# find something in the output like 
# /usr/local/Cellar/openal-soft/1.21.1/lib/libopenal.1.21.1.dylib

# copy this file to local lib path
sudo cp /usr/local/Cellar/openal-soft/1.21.1/lib/libopenal.1.21.1.dylib /usr/local/lib/libopenal.dylib