Exemple #1
0
 public virtual void Stop()
 {
     StopSource();
     AL.Source(Source, ALSourcei.Buffer, 0);
 }
Exemple #2
0
            public OpenAlAsyncLoadSound(int source, bool looping, bool relative, Vector3 pos,
                                        float volume, int channels, int sampleBits, int sampleRate, System.IO.Stream stream) : base(source, looping, relative, pos, volume, sampleRate)
            {
                var silentSource = new OpenAlSoundSource(SilentDta, channels, sampleBits, sampleRate);

                AL.Source(source, ALSourcei.Buffer, (int)silentSource.Buffer);

                playTask = Task.Run(async() =>
                {
                    System.IO.MemoryStream memoryStream;
                    using (stream)
                    {
                        memoryStream = new MemoryStream();
                        try
                        {
                            await stream.CopyToAsync(memoryStream, 81920, cts.Token);
                        }
                        catch (TaskCanceledException)
                        {
                            AL.SourceStop(source);
                            AL.Source(source, ALSourcei.Buffer, 0);
                            silentSource.Dispose();
                            return;
                        }
                    }

                    var data           = memoryStream.ToArray();
                    var bytesPerSample = sampleBits / 8f;
                    var lengthInSecs   = data.Length / (channels * bytesPerSample * sampleRate);
                    using (var soundSource = new OpenAlSoundSource(data, channels, sampleBits, sampleRate))
                    {
                        AL.SourceStop(source);
                        AL.Source(source, ALSourcei.Buffer, (int)soundSource.Buffer);
                        silentSource.Dispose();

                        lock (cts)
                        {
                            if (!cts.IsCancellationRequested)
                            {
                                int state;
                                AL.GetSource(Source, ALGetSourcei.SourceState, out state);
                                if (state != (int)ALSourceState.Stopped)
                                {
                                    AL.SourcePlay(source);
                                }
                                else
                                {
                                    AL.SourceRewind((uint)source);
                                }
                            }
                        }

                        while (!cts.IsCancellationRequested)
                        {
                            var currentSeek = SeekPosition;

                            int state;
                            AL.GetSource(Source, ALGetSourcei.SourceState, out state);
                            if (state == (int)ALSourceState.Stopped)
                            {
                                break;
                            }

                            try
                            {
                                var delaySecs = Math.Max(lengthInSecs - currentSeek, 1 / 60f);
                                await Task.Delay(TimeSpan.FromSeconds(delaySecs), cts.Token);
                            }
                            catch (TaskCanceledException)
                            {
                            }
                        }

                        AL.Source(Source, ALSourcei.Buffer, 0);
                    }
                });
            }
Exemple #3
0
 public OpenAlSound(int source, bool looping, bool relative, Vector3 pos, float volume, int sampleRate, uint buffer) : this(source, looping, relative, pos, volume, sampleRate)
 {
     AL.Source(source, ALSourcei.Buffer, (int)buffer);
     AL.SourcePlay(source);
 }
Exemple #4
0
 public void SetPosition(Vector3 pos)
 {
     AL.Source(Source, ALSource3f.Position, pos.X, pos.Y, pos.Z);
 }
Exemple #5
0
        /// <summary>
        /// Open the sound device, sets up an audio context, and makes the new context
        /// the current context. Note that this method will stop the playback of
        /// music that was running prior to the game start. If any error occurs, then
        /// the state of the controller is reset.
        /// </summary>
        /// <returns>True if the sound controller was setup, and false if not.</returns>
        private bool OpenSoundController()
        {
            try
            {
                _device = Alc.OpenDevice(string.Empty);
                EffectsExtension.device = _device;
            }
            catch (DllNotFoundException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw new NoAudioHardwareException("OpenAL device could not be initialized.", ex);
            }

            AlcHelper.CheckError("Could not open OpenAL device");

            if (_device != IntPtr.Zero)
            {
#if ANDROID
                // Attach activity event handlers so we can pause and resume all playing sounds
                AndroidGameView.OnPauseGameThread  += Activity_Paused;
                AndroidGameView.OnResumeGameThread += Activity_Resumed;

                // Query the device for the ideal frequency and update buffer size so
                // we can get the low latency sound path.

                /*
                 * The recommended sequence is:
                 *
                 * Check for feature "android.hardware.audio.low_latency" using code such as this:
                 * import android.content.pm.PackageManager;
                 * ...
                 * PackageManager pm = getContext().getPackageManager();
                 * boolean claimsFeature = pm.hasSystemFeature(PackageManager.FEATURE_AUDIO_LOW_LATENCY);
                 * Check for API level 17 or higher, to confirm use of android.media.AudioManager.getProperty().
                 * Get the native or optimal output sample rate and buffer size for this device's primary output stream, using code such as this:
                 * import android.media.AudioManager;
                 * ...
                 * AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                 * String sampleRate = am.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE));
                 * String framesPerBuffer = am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER));
                 * Note that sampleRate and framesPerBuffer are Strings. First check for null and then convert to int using Integer.parseInt().
                 * Now use OpenSL ES to create an AudioPlayer with PCM buffer queue data locator.
                 *
                 * See http://stackoverflow.com/questions/14842803/low-latency-audio-playback-on-android
                 */

                int frequency     = DEFAULT_FREQUENCY;
                int updateSize    = DEFAULT_UPDATE_SIZE;
                int updateBuffers = DEFAULT_UPDATE_BUFFER_COUNT;
                if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.JellyBeanMr1)
                {
                    Android.Util.Log.Debug("OAL", Game.Activity.PackageManager.HasSystemFeature(PackageManager.FeatureAudioLowLatency) ? "Supports low latency audio playback." : "Does not support low latency audio playback.");

                    var audioManager = Game.Activity.GetSystemService(Context.AudioService) as AudioManager;
                    if (audioManager != null)
                    {
                        var result = audioManager.GetProperty(AudioManager.PropertyOutputSampleRate);
                        if (!string.IsNullOrEmpty(result))
                        {
                            frequency = int.Parse(result, CultureInfo.InvariantCulture);
                        }
                        result = audioManager.GetProperty(AudioManager.PropertyOutputFramesPerBuffer);
                        if (!string.IsNullOrEmpty(result))
                        {
                            updateSize = int.Parse(result, CultureInfo.InvariantCulture);
                        }
                    }

                    // If 4.4 or higher, then we don't need to double buffer on the application side.
                    // See http://stackoverflow.com/a/15006327
                    //if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
                    //{
                    //    updateBuffers = 1;
                    //}
                }
                else
                {
                    Android.Util.Log.Debug("OAL", "Android 4.2 or higher required for low latency audio playback.");
                }
                Android.Util.Log.Debug("OAL", "Using sample rate " + frequency + "Hz and " + updateBuffers + " buffers of " + updateSize + " frames.");

                // These are missing and non-standard ALC constants
                const int AlcFrequency     = 0x1007;
                const int AlcUpdateSize    = 0x1014;
                const int AlcUpdateBuffers = 0x1015;

                int[] attribute = new[]
                {
                    AlcFrequency, frequency,
                    AlcUpdateSize, updateSize,
                    AlcUpdateBuffers, updateBuffers,
                    0
                };
#elif IOS
                EventHandler <AVAudioSessionInterruptionEventArgs> handler = delegate(object sender, AVAudioSessionInterruptionEventArgs e) {
                    switch (e.InterruptionType)
                    {
                    case AVAudioSessionInterruptionType.Began:
                        AVAudioSession.SharedInstance().SetActive(false);
                        Alc.MakeContextCurrent(IntPtr.Zero);
                        Alc.SuspendContext(_context);
                        break;

                    case AVAudioSessionInterruptionType.Ended:
                        AVAudioSession.SharedInstance().SetActive(true);
                        Alc.MakeContextCurrent(_context);
                        Alc.ProcessContext(_context);
                        break;
                    }
                };
                AVAudioSession.Notifications.ObserveInterruption(handler);

                int[] attribute = new int[0];
#else
                int[] attribute = new int[0];
#endif

                _context = Alc.CreateContext(_device, attribute);
#if DESKTOPGL
                _oggstreamer = new OggStreamer();
#endif

                AlcHelper.CheckError("Could not create OpenAL context");

                if (_context != NullContext)
                {
                    Alc.MakeContextCurrent(_context);
                    AlcHelper.CheckError("Could not make OpenAL context current");
                    SupportsIma4  = AL.IsExtensionPresent("AL_EXT_IMA4");
                    SupportsAdpcm = AL.IsExtensionPresent("AL_SOFT_MSADPCM");
                    SupportsEfx   = AL.IsExtensionPresent("AL_EXT_EFX");
                    SupportsIeee  = AL.IsExtensionPresent("AL_EXT_float32");
                    return(true);
                }
            }
            return(false);
        }
Exemple #6
0
 public OpenAlSoundSource(byte[] data, int channels, int sampleBits, int sampleRate)
 {
     SampleRate = sampleRate;
     AL.GenBuffers(1, out buffer);
     AL.BufferData(buffer, OpenALSoundController.MakeALFormat(channels, sampleBits), data, data.Length, sampleRate);
 }
Exemple #7
0
 internal void BindFilterToSource(int sourceId, int filterId)
 {
     AL.Source(sourceId, ALSourcei.EfxDirectFilter, filterId);
 }
Exemple #8
0
 internal void BindSourceToAuxiliarySlot(int SourceId, int slot, int slotnumber, int filter)
 {
     AL.Source(SourceId, ALSourcei.EfxAuxilarySendFilter, slot, slotnumber, filter);
 }
Exemple #9
0
        internal EffectsExtension()
        {
            IsInitialized = false;
            if (!Alc.IsExtensionPresent(device, "ALC_EXT_EFX"))
            {
                return;
            }

            alGenEffects                 = (alGenEffectsDelegate)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGenEffects"), typeof(alGenEffectsDelegate));
            alDeleteEffects              = (alDeleteEffectsDelegate)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alDeleteEffects"), typeof(alDeleteEffectsDelegate));
            alEffectf                    = (alEffectfDelegate)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alEffectf"), typeof(alEffectfDelegate));
            alEffecti                    = (alEffectiDelegate)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alEffecti"), typeof(alEffectiDelegate));
            alGenAuxiliaryEffectSlots    = (alGenAuxiliaryEffectSlotsDelegate)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGenAuxiliaryEffectSlots"), typeof(alGenAuxiliaryEffectSlotsDelegate));
            alDeleteAuxiliaryEffectSlots = (alDeleteAuxiliaryEffectSlotsDelegate)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alDeleteAuxiliaryEffectSlots"), typeof(alDeleteAuxiliaryEffectSlotsDelegate));
            alAuxiliaryEffectSloti       = (alAuxiliaryEffectSlotiDelegate)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alAuxiliaryEffectSloti"), typeof(alAuxiliaryEffectSlotiDelegate));
            alAuxiliaryEffectSlotf       = (alAuxiliaryEffectSlotfDelegate)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alAuxiliaryEffectSlotf"), typeof(alAuxiliaryEffectSlotfDelegate));

            alGenFilters    = (alGenFiltersDelegate)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alGenFilters"), typeof(alGenFiltersDelegate));
            alFilteri       = (alFilteriDelegate)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alFilteri"), typeof(alFilteriDelegate));
            alFilterf       = (alFilterfDelegate)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alFilterf"), typeof(alFilterfDelegate));
            alDeleteFilters = (alDeleteFiltersDelegate)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("alDeleteFilters"), typeof(alDeleteFiltersDelegate));

            IsInitialized = true;
        }
Exemple #10
0
 internal XRamExtension()
 {
     IsInitialized = false;
     if (!AL.IsExtensionPresent("EAX-RAM"))
     {
         return;
     }
     RamSize           = AL.GetEnumValue("AL_EAX_RAM_SIZE");
     RamFree           = AL.GetEnumValue("AL_EAX_RAM_FREE");
     StorageAuto       = AL.GetEnumValue("AL_STORAGE_AUTOMATIC");
     StorageHardware   = AL.GetEnumValue("AL_STORAGE_HARDWARE");
     StorageAccessible = AL.GetEnumValue("AL_STORAGE_ACCESSIBLE");
     if (RamSize == 0 || RamFree == 0 || StorageAuto == 0 || StorageHardware == 0 || StorageAccessible == 0)
     {
         return;
     }
     try
     {
         setBufferMode = (XRamExtension.SetBufferModeDelegate)Marshal.GetDelegateForFunctionPointer(AL.GetProcAddress("EAXSetBufferMode"), typeof(XRamExtension.SetBufferModeDelegate));
     }
     catch (Exception)
     {
         return;
     }
     IsInitialized = true;
 }
Exemple #11
0
 internal unsafe static void SourceQueueBuffer(int sourceId, int buffer)
 {
     AL.SourceQueueBuffers(sourceId, 1, &buffer);
 }