Search code examples
c#opentkopenal

Sound does not play in 'OpenTK.OpenAL 4.x'


I am upgrading from OpenTK 3.3.3 to OpenTK 4.7.7.

The migrated code below doesn't work.
(There are no errors, no sound.)

        //OpenTK.OpenAL 4.7.7
        var device = ALC.OpenDevice(null);
        var context = ALC.CreateContext(device, new ALContextAttributes());
        ALC.MakeContextCurrent(context);

        int bufferId = AL.GenBuffer();
        int sourceId = AL.GenSource();

        int channels, bits_per_sample, sample_rate;
        byte[] soundData = LoadWave(
            File.Open(sFileName, FileMode.Open),
            out channels,
            out bits_per_sample,
            out sample_rate);
        AL.BufferData(bufferId
            , GetSoundFormat(channels, bits_per_sample)
            , soundData
            , bits_per_sample);

        AL.Source(sourceId, ALSourcei.Buffer, bufferId);
        AL.Source(sourceId, ALSourceb.Looping, true);
        AL.SourcePlay(sourceId);

The code that worked in OpenTK 3.3.3 is as follows.

        //OpenTK 3.3.3
        AudioContext context = new AudioContext();

        int bufferId = AL.GenBuffer();
        int sourceId = AL.GenSource();
        int state;

        int channels, bits_per_sample, sample_rate;
        byte[] sound_data = LoadWave(
            File.Open(filename, FileMode.Open)
            , out channels
            , out bits_per_sample
            , out sample_rate);
        AL.BufferData(
            bufferId
            , GetSoundFormat(channels, bits_per_sample)
            , sound_data
            , sound_data.Length
            , sample_rate);

        AL.Source(sourceId, ALSourcei.Buffer, bufferId);
        AL.Source(sourceId, ALSourceb.Looping, true);
        AL.SourcePlay(sourceId);

OpenTK.OpenAL 4.7.7 test project(github)

OpenTK 3.3.3 test project(github)


This is a code I made using code that other people are using on the Internet.

Looking at the OpenTK 3.3.3 code, it seems to work, but I would like to know where the problem is.


Solution

  • I found the following article through a search.

    opentk issues

    Referring to the code here, I modified it as follows.
    It works the way you want it to.

    IntPtr unmanagedPointer = Marshal.AllocHGlobal(sound_data.Length);
    Marshal.Copy(sound_data, 0, unmanagedPointer, sound_data.Length);
    
    AL.BufferData(
        bufferId
        , GetSoundFormat(channels, bits_per_sample)
        , unmanagedPointer
        , sound_data.Length
        , sample_rate);
    

    The full code can be found 'here'.