// is playing
 internal static bool IsPlaying(int SoundSourceIndex)
 {
     if (OpenAlContext != IntPtr.Zero)
     {
         if (SoundSourceIndex >= 0 && SoundSourceIndex < SoundSources.Length && SoundSources[SoundSourceIndex] != null)
         {
             if (SoundSources[SoundSourceIndex].Suppressed)
             {
                 return(true);
             }
             else
             {
                 if (SoundSources[SoundSourceIndex].OpenAlSourceIndex.Valid)
                 {
                     int i = SoundSources[SoundSourceIndex].OpenAlSourceIndex.Index;
                     int state;
                     Al.alGetSourcei(i, Al.AL_SOURCE_STATE, out state);
                     return(state == Al.AL_PLAYING);
                 }
                 else
                 {
                     return(false);
                 }
             }
         }
         else
         {
             return(false);
         }
     }
     else
     {
         return(false);
     }
 }
        private bool IsChannelPlaying(int channel)
        {
            int value = 0;

            Al.alGetSourcei(channel, Al.AL_SOURCE_STATE, out value);
            return(value == Al.AL_PLAYING);
        }
Beispiel #3
0
        protected override void OnSetListener(Vector3 position, Vector3 velocity, Quaternion rotation)
        {
            criticalSection.Enter();

            //!!!!double

            Al.alListener3f(Al.AL_POSITION, (float)position.X, (float)position.Y, (float)position.Z);
            Al.alListener3f(Al.AL_VELOCITY, (float)velocity.X, (float)velocity.Y, (float)velocity.Z);

            var forward = rotation.GetForward();
            var up      = rotation.GetUp();

            unsafe
            {
                fixed(float *orientation = tempFloatArray6)
                {
                    orientation[0] = (float)forward.X;
                    orientation[1] = (float)forward.Y;
                    orientation[2] = (float)forward.Z;
                    orientation[3] = (float)up.X;
                    orientation[4] = (float)up.Y;
                    orientation[5] = (float)up.Z;
                    Al.alListenerfv(Al.AL_ORIENTATION, orientation);
                }
            }

            CheckError();

            criticalSection.Leave();
        }
Beispiel #4
0
        public bool Playback()
        {
            int queue = 0;

            Al.alGetSourcei(source, Al.AL_BUFFERS_QUEUED, out queue);

            if (queue > 0)
            {
                Al.alSourcePlay(source);
            }

            if (Playing())
            {
                return(true);
            }

            for (int i = 0; i < MAX_BUFFERS; ++i)
            {
                if (!Stream(buffers[i]))
                {
                    return(false);
                }
            }

            Al.alSourceQueueBuffers(source, MAX_BUFFERS, buffers);

            return(true);
        }
Beispiel #5
0
        public AudioEngine(string settingsFile, TimeSpan lookAheadTime, string rendererId)
        {
            Alut.alutInit();

            // Generate an OpenAL source.
            Al.alGenSources(1, out source);
            if (Al.alGetError() != Al.AL_NO_ERROR)
            {
                //ERROR
            }

            Al.alSourcef(source, Al.AL_PITCH, 1.0f);
            Al.alSourcef(source, Al.AL_GAIN, 1.0f);
            //Al.alSourcefv(source, Al.AL_POSITION, sourcePosition);
            //Al.alSourcefv(source, Al.AL_VELOCITY, sourceVelocity);
            Al.alSourcei(source, Al.AL_LOOPING, 0);

            // Do a final error check and then return.
            if (Al.alGetError() == Al.AL_NO_ERROR)
            {
                //ERROR
            }

            float[] listenerPosition    = { 0, 0, 0 };
            float[] listenerVelocity    = { 0, 0, 0 };
            float[] listenerOrientation = { 0, 0, -1, 0, 1, 0 };

            Al.alListenerfv(Al.AL_POSITION, listenerPosition);
            Al.alListenerfv(Al.AL_VELOCITY, listenerVelocity);
            Al.alListenerfv(Al.AL_ORIENTATION, listenerOrientation);
        }
Beispiel #6
0
        public OpenAlSoundEngine()
        {
            //var str = Alc.alcGetString(IntPtr.Zero, Alc.ALC_DEFAULT_DEVICE_SPECIFIER);
            var dev = Alc.alcOpenDevice(null);

            if (dev == IntPtr.Zero)
            {
                throw new InvalidOperationException("Can't create OpenAL device");
            }
            var ctx = Alc.alcCreateContext(dev, IntPtr.Zero);

            if (ctx == IntPtr.Zero)
            {
                throw new InvalidOperationException("Can't create OpenAL context");
            }
            Alc.alcMakeContextCurrent(ctx);

            for (var i = 0; i < POOL_SIZE; i++)
            {
                var source = 0;
                Al.alGenSources(1, out source);
                if (0 != Al.alGetError())
                {
                    Log.Write("debug", "Failed generating OpenAL source {0}", i);
                    return;
                }

                sourcePool.Add(source, new PoolSlot()
                {
                    isActive = false
                });
            }
        }
Beispiel #7
0
        public OpenALAudioLayer(string name, OpenALAudioAdapter parent) : base(name)
        {
            if (_openALFormatId == 0)
            {
                _openALFormatId = _openALAudioFormat.BitsPerSample switch
                {
                    32 => Al.FORMAT_STEREO32F,
                    16 => _openALAudioFormat.Channels == 2 ? Al.FORMAT_STEREO16 : Al.FORMAT_MONO16,
                    8 => _openALAudioFormat.Channels == 2 ? Al.FORMAT_STEREO8 : Al.FORMAT_MONO8,
                    _ => _openALFormatId
                }
            }
            ;

            if (_frameRequestSize == 0)
            {
                _frameRequestSize  = _openALAudioFormat.GetFrameCount(BackendBufferExpectedAhead / 1000f);
                _frameRequestSize /= BUFFER_COUNT;
            }

            _parent = parent;
            Al.GenSource(out _source);

            _buffers    = new uint[BUFFER_COUNT];
            _bufferBusy = new bool[BUFFER_COUNT];
            for (var i = 0; i < _buffers.Length; i++)
            {
                Al.GenBuffer(out _buffers[i]);
            }

            _uploadBuffer = new byte[_frameRequestSize * _openALAudioFormat.FrameSize];
        }
Beispiel #8
0
        public virtual void DeleteALBuffers()
        {
            Owner.KillChannels(this);
            if (alBuffer != 0)
            {
                if (!Al.IsBuffer(alBuffer))
                {
                    throw new Exception("Buffer to delete is invalid!");
                }

                Al.DeleteBuffer(alBuffer); alBuffer = 0;

                int alError = Al.GetError();
                if (alError != Al.NoError)
                {
                    throw new Exception("Failed to delete OpenAL buffer for non-streamed sound: " + Al.GetErrorString(alError));
                }
            }
            if (alMuffledBuffer != 0)
            {
                if (!Al.IsBuffer(alMuffledBuffer))
                {
                    throw new Exception("Buffer to delete is invalid!");
                }

                Al.DeleteBuffer(alMuffledBuffer); alMuffledBuffer = 0;

                int alError = Al.GetError();
                if (alError != Al.NoError)
                {
                    throw new Exception("Failed to delete OpenAL buffer for non-streamed sound: " + Al.GetErrorString(alError));
                }
            }
        }
Beispiel #9
0
        public bool BufferFinished()
        {
            // Get number of finished buffers
            int processed;

            Al.alGetSourcei(source, Al.AL_BUFFERS_PROCESSED, out processed);

            if (processed > 0)
            {
                // Remove finished buffers from queue
                int[] finished = new int[processed];
                Al.alSourceUnqueueBuffers(source, processed, finished);

                // Add finished buffers to free queue
                lock (buffers)
                {
                    foreach (int i in finished)
                    {
                        buffers.Enqueue(i);
                        Monitor.Pulse(buffers);
                    }
                }
            }

            // Return if we have finished buffers
            lock (buffers)
            {
                return(buffers.Count > 0);
            }
        }
Beispiel #10
0
 public void stopSound()
 {
     if (Assets.Instance.Sounds.ContainsKey(this.SoundName))
     {
         Al.alSourceStop(Assets.Instance.Sounds[this.SoundName].SoundID);
     }
 }
Beispiel #11
0
        public virtual void InitializeALBuffers()
        {
            if (!Stream)
            {
                Al.GenBuffer(out alBuffer);
                int alError = Al.GetError();
                if (alError != Al.NoError)
                {
                    throw new Exception("Failed to create OpenAL buffer for non-streamed sound: " + Al.GetErrorString(alError));
                }

                if (!Al.IsBuffer(alBuffer))
                {
                    throw new Exception("Generated OpenAL buffer is invalid!");
                }

                Al.GenBuffer(out alMuffledBuffer);
                alError = Al.GetError();
                if (alError != Al.NoError)
                {
                    throw new Exception("Failed to create OpenAL buffer for non-streamed sound: " + Al.GetErrorString(alError));
                }

                if (!Al.IsBuffer(alMuffledBuffer))
                {
                    throw new Exception("Generated OpenAL buffer is invalid!");
                }
            }
            else
            {
                alBuffer = 0;
            }
        }
Beispiel #12
0
 public void playSound()
 {
     if (Assets.Instance.Sounds.ContainsKey(this.SoundName))
     {
         Al.alSourcePlay(Assets.Instance.Sounds[this.SoundName].SoundID);
     }
 }
Beispiel #13
0
 public void setSoundPosition(Vector3D p)
 {
     if (Assets.Instance.Sounds.ContainsKey(this.SoundName))
     {
         Al.alSource3f(Assets.Instance.Sounds[this.SoundName].SoundID, Al.AL_POSITION, (float)p.Px, (float)p.Py, (float)p.Pz);
     }
 }
Beispiel #14
0
        internal unsafe AudioClip(IResource resource)
        {
            Al.GenBuffer(out Buffer);

            using var reader = new VorbisReader(resource.OpenStream());

            var channels   = reader.Channels;
            var sampleRate = reader.SampleRate;
            var seconds    = reader.TotalTime.TotalSeconds;
            var samples    = (int)Math.Ceiling(seconds * sampleRate * channels);

            var floats = new Span <float>(new float[samples]);

            if (reader.ReadSamples(floats) <= 0)
            {
                throw new Exception("Failed to read OGG stream.");
            }

            var shorts = new Span <short>(new short[samples]); // 16 bit

            for (var i = 0; i < floats.Length; i++)
                shorts[i] = (short)(short.MaxValue * floats[i]);

            fixed(void *p = &shorts.GetPinnableReference())
            {
                Al.BufferData(Buffer, channels == 2 ? Al.FormatStereo16 : Al.FormatMono16, p, shorts.Length * sizeof(short), sampleRate);
            }
        }
Beispiel #15
0
        public bool BindToBuffer(Sound bufferToBindTo)
        {
            if (m_SourceHandle == -1)
            {
                return(false);
            }

            // Bind the buffer with the source.
#if USE_OPENAL
            Al.alSourcei(m_SourceHandle, Al.AL_BUFFER, bufferToBindTo.m_BufferHandle);
            Al.alSourcef(m_SourceHandle, Al.AL_PITCH, 1.0f);
            Al.alSourcef(m_SourceHandle, Al.AL_GAIN, 1.0f);
            Al.alSourcefv(m_SourceHandle, Al.AL_POSITION, m_SourcePosition);
            Al.alSourcefv(m_SourceHandle, Al.AL_VELOCITY, m_SourceVelocity);
            Al.alSourcei(m_SourceHandle, Al.AL_LOOPING, bufferToBindTo.m_Loop);

            // Do a final error check and then return.
            if (Al.alGetError() == Al.AL_NO_ERROR)
            {
                return(true);
            }
#endif

            return(false);
        }
Beispiel #16
0
        public AudioSource()
        {
            // Open default device
            device = Alc.alcOpenDevice(null);
            if (device == IntPtr.Zero)
            {
                throw new Exception("Unable to open OpenAL device");
            }

            // Create context
            context = Alc.alcCreateContext(device, IntPtr.Zero);
            if (context == IntPtr.Zero)
            {
                throw new Exception("Unable to create OpenAL context");
            }
            int rv = Alc.alcMakeContextCurrent(context);

            // Create buffers
            for (int i = 0; i < 8; ++i)
            {
                int b;
                Al.alGenBuffers(1, out b);
                buffers.Enqueue(b);
            }

            // Create source
            Al.alGenSources(1, out source);
        }
Beispiel #17
0
        public override void end()
        {
            if (this.Type == SnowType.Normal)
            {
                if (Assets.Instance.Sounds.ContainsKey("Vento"))
                {
                    Al.alSourceStop(Assets.Instance.Sounds["Vento"].SoundID);
                }
            }
            else if (this.Type == SnowType.Light)
            {
                if (Assets.Instance.Sounds.ContainsKey("Vento"))
                {
                    Al.alSourceStop(Assets.Instance.Sounds["Vento"].SoundID);
                }
            }
            else if (this.Type == SnowType.Strong)
            {
                if (Assets.Instance.Sounds.ContainsKey("Vento"))
                {
                    Al.alSourceStop(Assets.Instance.Sounds["Vento"].SoundID);
                }
            }

            this.engine.ParticleList.Clear();
            Gl.glDisable(Gl.GL_FOG);
        }
Beispiel #18
0
        protected override void OnSetListener(Vec3 position, Vec3 velocity, Vec3 forward, Vec3 up)
        {
            criticalSection.Enter();

            Al.alListener3f(Al.AL_POSITION, position.X, position.Y, position.Z);
            Al.alListener3f(Al.AL_VELOCITY, velocity.X, velocity.Y, velocity.Z);

            unsafe
            {
                fixed(float *orientation = tempFloatArray6)
                {
                    orientation[0] = forward.X;
                    orientation[1] = forward.Y;
                    orientation[2] = forward.Z;
                    orientation[3] = up.X;
                    orientation[4] = up.Y;
                    orientation[5] = up.Z;
                    Al.alListenerfv(Al.AL_ORIENTATION, orientation);
                }
            }

            CheckError();

            criticalSection.Leave();
        }
Beispiel #19
0
        private void DequeueBusyBuffers()
        {
            // Check if any are done.
            Al.GetSourcei(_source, Al.BUFFERS_PROCESSED, out int buffersProcessed);
            if (buffersProcessed == 0)
            {
                return;
            }

            // Dequeue and mark as free.
            var removed = new uint[buffersProcessed];

            Al.SourceUnqueueBuffers(_source, buffersProcessed, removed);
            for (var i = 0; i < buffersProcessed; i++)
            {
                uint bufferId = removed[i];
                for (var bIdx = 0; bIdx < _buffers.Length; bIdx++)
                {
                    if (_buffers[bIdx] == bufferId)
                    {
                        _bufferBusy[bIdx] = false;
                    }
                }
            }
        }
Beispiel #20
0
        public override void InitializeALBuffers()
        {
            base.InitializeALBuffers();

            reader ??= new VorbisReader(Filename);

            ALFormat   = reader.Channels == 1 ? Al.FormatMono16 : Al.FormatStereo16;
            SampleRate = reader.SampleRate;

            if (!Stream)
            {
                int bufferSize = (int)reader.TotalSamples * reader.Channels;

                float[] floatBuffer = new float[bufferSize];
                short[] shortBuffer = new short[bufferSize];

                int readSamples = reader.ReadSamples(floatBuffer, 0, bufferSize);

                playbackAmplitude = new List <float>();
                for (int i = 0; i < bufferSize; i += reader.Channels * AMPLITUDE_SAMPLE_COUNT)
                {
                    float maxAmplitude = 0.0f;
                    for (int j = i; j < i + reader.Channels * AMPLITUDE_SAMPLE_COUNT; j++)
                    {
                        if (j >= bufferSize)
                        {
                            break;
                        }
                        maxAmplitude = Math.Max(maxAmplitude, Math.Abs(floatBuffer[j]));
                    }
                    playbackAmplitude.Add(maxAmplitude);
                }

                CastBuffer(floatBuffer, shortBuffer, readSamples);

                Al.BufferData(ALBuffer, ALFormat, shortBuffer,
                              readSamples * sizeof(short), SampleRate);

                int alError = Al.GetError();
                if (alError != Al.NoError)
                {
                    throw new Exception("Failed to set buffer data for non-streamed audio! " + Al.GetErrorString(alError));
                }

                MuffleBuffer(floatBuffer, SampleRate, reader.Channels);

                CastBuffer(floatBuffer, shortBuffer, readSamples);

                Al.BufferData(ALMuffledBuffer, ALFormat, shortBuffer,
                              readSamples * sizeof(short), SampleRate);

                alError = Al.GetError();
                if (alError != Al.NoError)
                {
                    throw new Exception("Failed to set buffer data for non-streamed audio! " + Al.GetErrorString(alError));
                }

                reader.Dispose(); reader = null;
            }
        }
Beispiel #21
0
        public bool Playing()
        {
            int state;

            Al.alGetSourcei(source, Al.AL_SOURCE_STATE, out state);
            return(state == Al.AL_PLAYING);
        }
        unsafe protected override void PreDetachVirtualChannel()
        {
            OpenALSoundWorld.criticalSection.Enter();

            Al.alSourceStop(alSource);
            OpenALSoundWorld.CheckError();

            if (currentSound is OpenALDataBufferSound)
            {
                if (currentSound is OpenALFileStreamSound)
                {
                    OpenALSoundWorld.Instance.fileStreamRealChannels.Remove(this);
                }

                if (streamBuffer != null)
                {
                    NativeUtils.Free((IntPtr)streamBuffer);
                    streamBuffer     = null;
                    streamBufferSize = 0;
                }
            }

            Al.alSourcei(alSource, Al.AL_BUFFER, 0);
            OpenALSoundWorld.CheckError();

            currentSound = null;

            OpenALSoundWorld.criticalSection.Leave();
        }
Beispiel #23
0
        private bool Update()
        {
            int  processed;
            bool active = true;

            Al.alGetSourcei(source, Al.AL_BUFFERS_PROCESSED, out processed);

            while (processed-- > 0)
            {
                int buffer = -1;

                Al.alSourceUnqueueBuffers(source, 1, ref buffer);
                Check();

                active = Stream(buffer);

                if (active)
                {
                    Al.alSourceQueueBuffers(source, 1, ref buffer);
                    Check();
                }
            }

            return(active);
        }
        void UpdatePosition2()
        {
            Vec3 value = CurrentVirtualChannel.Position;

            Al.alSource3f(alSource, Al.AL_POSITION, value.X, value.Y, value.Z);
            OpenALSoundWorld.CheckError();
        }
        public Sound PlaySound(string soundId, bool loop)
        {
            int channel = FindNextFreeChannel();

            if (channel != -1)
            {
                Al.alSourceStop(channel);
                Al.alSourcei(channel, Al.AL_BUFFER, _soundIdentifier[soundId]._bufferId);
                Al.alSourcef(channel, Al.AL_PITCH, 1.0f);
                Al.alSourcef(channel, Al.AL_GAIN, 1.0f);

                if (loop)
                {
                    Al.alSourcei(channel, Al.AL_LOOPING, 1);
                }
                else
                {
                    Al.alSourcei(channel, Al.AL_LOOPING, 0);
                }
                Al.alSourcef(channel, Al.AL_GAIN, _masterVolume);
                Al.alSourcePlay(channel);
                return(new Sound(channel));
            }
            else
            {
                // Error sound
                return(new Sound(-1));
            }
        }
        void UpdateVelocity2()
        {
            Vec3 value = CurrentVirtualChannel.Velocity;

            Al.alSource3f(alSource, Al.AL_VELOCITY, value.X, value.Y, value.Z);
            OpenALSoundWorld.CheckError();
        }
Beispiel #27
0
        //

        internal static bool CheckError()
        {
            int error = Al.alGetError();

            if (error == Al.AL_NO_ERROR)
            {
                return(false);
            }

            string text;

            switch (error)
            {
            case Al.AL_INVALID_ENUM: text = "Invalid enum"; break;

            case Al.AL_INVALID_VALUE: text = "Invalid value"; break;

            case Al.AL_INVALID_OPERATION: text = "Invalid operation"; break;

            case Al.AL_OUT_OF_MEMORY: text = "Out of memory"; break;

            case Al.AL_INVALID_NAME: text = "Invalid name"; break;

            default: text = string.Format("Unknown error ({0})", error); break;
            }

            Log.Warning("OpenALSoundSystem: Internal error: {0}.", text);

            return(true);
        }
        void UpdateVolume2()
        {
            float value = CurrentVirtualChannel.GetTotalVolume() * CurrentVirtualChannel.GetRolloffFactor();

            Al.alSourcef(alSource, Al.AL_GAIN, value);
            OpenALSoundWorld.CheckError();
        }
Beispiel #29
0
 // --- Event Handlers ---
 #region Timer_Elapsed(object source, ElapsedEventArgs e)
 private static void Timer_Elapsed(object s, ElapsedEventArgs e)
 {
     sourcePosition[0] += sourceVelocity[0];
     sourcePosition[1] += sourceVelocity[1];
     sourcePosition[2] += sourceVelocity[2];
     Al.alSourcefv(source, Al.AL_POSITION, sourcePosition);
 }
Beispiel #30
0
        public void PlayAnAvailableCopy()
        {
            SoundSource <T> soundToBindAndPlay = null;

            if (s_AvailableSoundSources.Count < s_MaxSimultaneousSounds)
            {
                soundToBindAndPlay = new SoundSource <T>();
                s_AvailableSoundSources.Add(soundToBindAndPlay);
            }
            else
            {
                // Find the first sound not playing.
                foreach (SoundSource <T> notPlayingSound in s_AvailableSoundSources)
                {
                    int playingValue;
                    Al.alGetSourcei(notPlayingSound.m_SourceHandle, (int)Al.AL_SOURCE_STATE, out playingValue);
                    if (playingValue == (int)Al.AL_STOPPED)
                    {
                        soundToBindAndPlay = notPlayingSound;
                        break;
                    }
                }

                // TODO: No sound is available that is not playing.  Find the quietest sound and if it is quieter than
                // the sound we are about to play than play it.
            }

            if (soundToBindAndPlay != null)
            {
                soundToBindAndPlay.BindToBuffer(this);
                soundToBindAndPlay.Play();
            }
        }