Example #1
0
        private void AudioPlayerThread()
        {
            var iTotalBuffersProcessed = 0;
            var uiBuffer = new uint[1];

            Al.GenSources(1, out uint[] source);
            Al.GenBuffers(NumBuffers, out uint[] buffer);

            var data = new short[DataChunckSize];

            // Fill all the buffers with audio data from the wave file
            foreach (var id in buffer)
            {
                Buffer(data, id);
            }
            Al.SourceQueueBuffers(source[0], buffer.Length, buffer);
            Al.SourcePlay(source[0]);

            bool playing = true;

            while (playing)
            {
                Thread.Sleep(10); // Sleep 10 msec periodically

                Al.GetSourcei(source[0], Al.BuffersProcessed, out int iBuffersProcessed);

                iTotalBuffersProcessed += iBuffersProcessed;
                Console.Write("\rBuffers Processed {0}", iTotalBuffersProcessed);

                // For each processed buffer, remove it from the source queue, read the next chunk of
                // audio data from the file, fill the buffer with new data, and add it to the source queue
                while (iBuffersProcessed > 0)
                {
                    // Remove the buffer from the queue (uiBuffer contains the buffer ID for the dequeued buffer)
                    Al.SourceUnqueueBuffers(source[0], 1, uiBuffer);

                    // Read more pData audio data (if there is any)
                    if (Buffer(data, uiBuffer[0]) > 0)
                    {
                        // Insert the audio buffer to the source queue
                        Al.SourceQueueBuffers(source[0], 1, uiBuffer);
                    }
                    Al.GetSourcei(source[0], Al.SourceState, out var state);
                    if (state != Al.Playing)
                    {
                        playing = false;
                    }

                    iBuffersProcessed--;
                }
            }

            Console.WriteLine();
            Console.WriteLine("End!");

            Al.SourceStop(source[0]);
            Al.DeleteSources(source.Length, source);
            Al.DeleteBuffers(buffer.Length, buffer);

            Alc.MakeContextCurrent(IntPtr.Zero);
            Alc.DestroyContext(_context);
            Alc.CloseDevice(_device);
        }