Ejemplo n.º 1
0
        public SoundManager()
        {
            loadedSounds      = new List <Sound>();
            streamingThread   = null;
            categoryModifiers = null;

            sourcePools = new SoundSourcePool[2];
            playingChannels[(int)SourcePoolIndex.Default] = new SoundChannel[SOURCE_COUNT];
            playingChannels[(int)SourcePoolIndex.Voice]   = new SoundChannel[16];

            string deviceName = GameMain.Config.AudioOutputDevice;

            if (string.IsNullOrEmpty(deviceName))
            {
                deviceName = Alc.GetString((IntPtr)null, Alc.DefaultDeviceSpecifier);
            }

#if (!OSX)
            var audioDeviceNames = Alc.GetStringList((IntPtr)null, Alc.AllDevicesSpecifier);
            if (audioDeviceNames.Any() && !audioDeviceNames.Any(n => n.Equals(deviceName, StringComparison.OrdinalIgnoreCase)))
            {
                deviceName = audioDeviceNames[0];
            }
#endif
            GameMain.Config.AudioOutputDevice = deviceName;

            InitializeAlcDevice(deviceName);

            ListenerPosition     = Vector3.Zero;
            ListenerTargetVector = new Vector3(0.0f, 0.0f, 1.0f);
            ListenerUpVector     = new Vector3(0.0f, -1.0f, 0.0f);

            CompressionDynamicRangeGain = 1.0f;
        }
Ejemplo n.º 2
0
        private void _audioOpenDevice()
        {
            // Load up ALC extensions.
            foreach (var extension in Alc.GetString(IntPtr.Zero, AlcGetString.Extensions).Split(' '))
            {
                _alcExtensions.Add(extension);
            }

            var preferredDevice = _configurationManager.GetCVar <string>("audio.device");

            // Open device.
            if (!string.IsNullOrEmpty(preferredDevice))
            {
                _openALDevice = Alc.OpenDevice(preferredDevice);
                if (_openALDevice == IntPtr.Zero)
                {
                    Logger.WarningS("oal", "Unable to open preferred audio device '{0}': {1}. Falling back default.",
                                    preferredDevice, Alc.GetError(IntPtr.Zero));

                    _openALDevice = Alc.OpenDevice(null);
                }
            }
            else
            {
                _openALDevice = Alc.OpenDevice(null);
            }

            _checkAlcError(_openALDevice);

            if (_openALDevice == IntPtr.Zero)
            {
                throw new InvalidOperationException($"Unable to open OpenAL device! {Alc.GetError(IntPtr.Zero)}");
            }
        }
Ejemplo n.º 3
0
 public static IEnumerable <string> GetDeviceNames()
 {
     if (!Alc.IsExtensionPresent(IntPtr.Zero, "ALC_ENUMERATION_EXT"))
     {
         return(Enumerable.Empty <string>());
     }
     return(Alc.GetString(IntPtr.Zero, AlcGetStringList.AllDevicesSpecifier));
 }
Ejemplo n.º 4
0
        public static void Init()
        {
            var deviceName = Alc.GetString(IntPtr.Zero, AlcGetString.DefaultAllDevicesSpecifier);

            Console.WriteLine(deviceName);
            _device  = Alc.OpenDevice(deviceName);
            _context = Alc.CreateContext(_device, (int[])null);
            Alc.MakeContextCurrent(_context);
            CheckError();
        }
Ejemplo n.º 5
0
        public AudioDevice(string device = null)
        {
            if (device == null)
            {
                device = Alc.GetString(IntPtr.Zero, AlcGetString.DefaultDeviceSpecifier);
            }

            deviceId      = Alc.OpenDevice(device);
            contextHandle = Alc.CreateContext(deviceId, new int[] { });
            this.Use();
        }
Ejemplo n.º 6
0
        static AudioDevice[] ToDeviceList(AlcGetStringList source)
        {
            var names = Alc.GetString(IntPtr.Zero, source);

            AudioDevice[] list = new AudioDevice[names.Count];

            for (int index = 0; index < names.Count; index++)
            {
                list[index] = Get(names[index]);
            }
            return(list);
        }
Ejemplo n.º 7
0
        public AlPlayer(IMusicPlayer player, int rate)
        {
            _player = player;
            _rate   = rate;

            _device  = Alc.OpenDevice(null);
            _context = Alc.CreateContext(_device, null);

            Console.WriteLine(Alc.GetString(IntPtr.Zero, Alc.AllDevicesSpecifier));

            Alc.MakeContextCurrent(_context);
        }
Ejemplo n.º 8
0
        internal static void PopulateCaptureDevices()
        {
            // clear microphones
            if (_allMicrophones != null)
            {
                _allMicrophones.Clear();
            }
            else
            {
                _allMicrophones = new List <Microphone>();
            }

            _default = null;

            // default device
            string defaultDevice = Alc.GetString(IntPtr.Zero, AlcGetString.CaptureDefaultDeviceSpecifier);

#if true //DESKTOPGL
            // enumerating capture devices
            IntPtr deviceList = Alc.alcGetString(IntPtr.Zero, (int)AlcGetString.CaptureDeviceSpecifier);

            // Marshal native UTF-8 character array to .NET string
            // The native string is a null-char separated list of known capture device specifiers ending with an empty string

            while (true)
            {
                var deviceIdentifier = InteropHelpers.Utf8ToString(deviceList);

                if (string.IsNullOrEmpty(deviceIdentifier))
                {
                    break;
                }

                var microphone = new Microphone(deviceIdentifier);
                _allMicrophones.Add(microphone);
                if (deviceIdentifier == defaultDevice)
                {
                    _default = microphone;
                }

                // increase the offset, add one extra for the terminator
                deviceList += deviceIdentifier.Length + 1;
            }
#else
            // Xamarin platforms don't provide an handle to alGetString that allow to marshal string arrays
            // so we're basically only adding the default microphone
            Microphone microphone = new Microphone(defaultDevice);
            _allMicrophones.Add(microphone);
            _default = microphone;
#endif
        }
Ejemplo n.º 9
0
        public static void Init()
        {
            ac = new AudioContext();
            ac.CheckErrors();
            ac.MakeCurrent();
            eax_sup = ac.SupportsExtension("EAX3.0");
            if (eax_sup)
            {
                xram = new XRamExtension();
            }

            mp3_sup = ac.SupportsExtension("AL_EXT_mp3");
            devices = Alc.GetString(IntPtr.Zero, AlcGetStringList.AllDevicesSpecifier);
        }
Ejemplo n.º 10
0
        static string[] QueryDevices(string label, AlcGetStringList type)
        {
            // Clear error bit
            AL.GetError();

            var devices = Alc.GetString(IntPtr.Zero, type).ToArray();

            if (AL.GetError() != ALError.NoError)
            {
                Log.Write("sound", "Failed to query OpenAL device list using {0}", label);
                return(new string[] { });
            }

            return(devices);
        }
Ejemplo n.º 11
0
        public AudioDevice(string device = null)
        {
            if (device == null)
            {
                device = Alc.GetString(IntPtr.Zero, AlcGetString.DefaultDeviceSpecifier);
            }

            deviceId = Alc.OpenDevice(device);
            if (deviceId == IntPtr.Zero)
            {
                throw new Exception("unable to open the specified audio device");
            }
            contextHandle = Alc.CreateContext(deviceId, new int[] { });
            this.Use();
        }
        public AlcDiagnostic(IntPtr dev)
        {
            Trace.WriteLine("--- Alc related errors ---");

            Alc.GetInteger(dev, AlcGetInteger.MajorVersion, 1, out MajorVersion);
            Alc.GetInteger(dev, AlcGetInteger.MinorVersion, 1, out MinorVersion);
            Alc.GetInteger(dev, AlcGetInteger.EfxMajorVersion, 1, out EfxMajorVersion);
            Alc.GetInteger(dev, AlcGetInteger.EfxMinorVersion, 1, out EfxMinorVersion);
            Alc.GetInteger(dev, AlcGetInteger.EfxMaxAuxiliarySends, 1, out EfxMaxAuxiliarySends);

            ExtensionString = Alc.GetString(dev, AlcGetString.Extensions);

            foreach (string s in Alc_Extension_C_Names)
            {
                Extensions.Add(s, Alc.IsExtensionPresent(dev, s));
            }
        }
        public static void checkForErrors()
        {
            {
                IntPtr   device = Alc.GetContextsDevice(Alc.GetCurrentContext());
                AlcError error  = Alc.GetError(device);

                if (error != AlcError.NoError)
                {
                    Trace.WriteLine("ALC ERROR: (" + error + ")  " + Alc.GetString(device, (AlcGetString)error));
                }
            }
            {
                ALError error = AL.GetError();
                if (error != ALError.NoError)
                {
                    Trace.WriteLine("AL ERROR: (" + error + ") " + AL.GetErrorString(error));
                }
            }
        }
Ejemplo n.º 14
0
        internal static void PopulateCaptureDevices()
        {
            // clear microphones
            if (_allMicrophones != null)
            {
                _allMicrophones.Clear();
            }
            else
            {
                _allMicrophones = new List <Microphone>();
            }

            _default = null;

            // default device
            string defaultDevice = Alc.GetString(IntPtr.Zero, AlcGetString.CaptureDefaultDeviceSpecifier);

#if true //DESKTOPGL
            // enumarating capture devices
            IntPtr deviceList = Alc.alGetString(IntPtr.Zero, (int)AlcGetString.CaptureDeviceSpecifier);
            // we need to marshal a string array
            string deviceIdentifier = Marshal.PtrToStringAnsi(deviceList);
            while (!String.IsNullOrEmpty(deviceIdentifier))
            {
                Microphone microphone = new Microphone(deviceIdentifier);
                _allMicrophones.Add(microphone);
                if (deviceIdentifier == defaultDevice)
                {
                    _default = microphone;
                }
                deviceList      += deviceIdentifier.Length + 1;
                deviceIdentifier = Marshal.PtrToStringAnsi(deviceList);
            }
#else
            // Xamarin platforms don't provide an handle to alGetString that allow to marshal string arrays
            // so we're basically only adding the default microphone
            Microphone microphone = new Microphone(defaultDevice);
            _allMicrophones.Add(microphone);
            _default = microphone;
#endif
        }
Ejemplo n.º 15
0
        public OpenALKeySoundPlayer()
        {
            String defaultDevice = Alc.GetString(IntPtr.Zero, AlcGetString.DefaultDeviceSpecifier);

            Device = Alc.OpenDevice(defaultDevice);
            if (Device == IntPtr.Zero)
            {
                Console.WriteLine("Failed to open default sound device");
                return;
            }

            context = Alc.CreateContext(Device, new int[] { });
            if (!Alc.MakeContextCurrent(context))
            {
                Console.WriteLine("failed to make default context");
                return;
            }

            AL.Listener(ALListener3f.Position, 0, 0, 0);
            AL.Listener(ALListener3f.Velocity, 0, 0, 0);
            AL.Listener(ALListenerfv.Orientation, ref ListenerOrientation);
        }
Ejemplo n.º 16
0
        public bool Initialize()
        {
            IntPtr         nullDevice = System.IntPtr.Zero;
            IList <string> allDevices = Alc.GetString(nullDevice, AlcGetStringList.DeviceSpecifier);

            foreach (string s in allDevices)
            {
                Logger.LogInfo("OpenAL device " + s);
            }

            // Open preferred device
            ContextHandle alContext;
            IntPtr        ALDevicePtr = Alc.OpenDevice(null);

            if (ALDevicePtr != null)
            {
                int[] deviceAttributes = null;
                alContext = Alc.CreateContext(ALDevicePtr, deviceAttributes);
                Alc.MakeContextCurrent(alContext);
            }
            else
            {
                Logger.LogError(Logger.ErrorState.Critical, "Could not get AL device");
                return(false);
            }

            string alRenderer = AL.Get(ALGetString.Renderer);
            string alVendor   = AL.Get(ALGetString.Vendor);
            string alVersion  = AL.Get(ALGetString.Version);

            Logger.LogInfo(string.Format("OpenAL Renderer {0}  Vendor {1}  Version {2}", alRenderer, alVendor, alVersion));


            Error.checkALError("initAudio");
            return(true);
        }
Ejemplo n.º 17
0
 public static string GetDevice()
 {
     return(Alc.GetString(Alc.OpenDevice(null), AlcGetString.DeviceSpecifier));
 }
Ejemplo n.º 18
0
        public void CreateSettingsFrame(Tab selectedTab = Tab.Graphics)
        {
            settingsFrame = new GUIFrame(new RectTransform(new Vector2(0.8f, 0.8f), GUI.Canvas, Anchor.Center));

            var settingsFramePadding = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.9f), settingsFrame.RectTransform, Anchor.TopCenter)
            {
                RelativeOffset = new Vector2(0.0f, 0.05f)
            })
            {
                RelativeSpacing = 0.01f, IsHorizontal = true
            };

            /// General tab --------------------------------------------------------------

            var leftPanel = new GUILayoutGroup(new RectTransform(new Vector2(0.25f, 1.0f), settingsFramePadding.RectTransform, Anchor.TopLeft));

            new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), leftPanel.RectTransform),
                             TextManager.Get("Settings"), textAlignment: Alignment.TopLeft, font: GUI.LargeFont);

            var generalLayoutGroup = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 1.0f), leftPanel.RectTransform, Anchor.TopLeft));

            new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), generalLayoutGroup.RectTransform), TextManager.Get("ContentPackages"));
            var contentPackageList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.75f), generalLayoutGroup.RectTransform))
            {
                CanBeFocused     = false,
                ScrollBarVisible = true
            };

            foreach (ContentPackage contentPackage in ContentPackage.List)
            {
                var tickBox = new GUITickBox(new RectTransform(new Point(32, 32), contentPackageList.Content.RectTransform), contentPackage.Name)
                {
                    UserData   = contentPackage,
                    OnSelected = SelectContentPackage,
                    Selected   = SelectedContentPackages.Contains(contentPackage)
                };
                if (!contentPackage.IsCompatible())
                {
                    tickBox.TextColor = Color.Red;
                    tickBox.Enabled   = false;
                    tickBox.ToolTip   = TextManager.Get(contentPackage.GameVersion <= new Version(0, 0, 0, 0) ? "IncompatibleContentPackageUnknownVersion" : "IncompatibleContentPackage")
                                        .Replace("[packagename]", contentPackage.Name)
                                        .Replace("[packageversion]", contentPackage.GameVersion.ToString())
                                        .Replace("[gameversion]", GameMain.Version.ToString());
                }
                else if (contentPackage.CorePackage && !contentPackage.ContainsRequiredCorePackageFiles(out List <ContentType> missingContentTypes))
                {
                    tickBox.TextColor = Color.Red;
                    tickBox.Enabled   = false;
                    tickBox.ToolTip   = TextManager.Get("ContentPackageMissingCoreFiles")
                                        .Replace("[packagename]", contentPackage.Name)
                                        .Replace("[missingfiletypes]", string.Join(", ", missingContentTypes));
                }
            }

            new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.045f), generalLayoutGroup.RectTransform), TextManager.Get("Language"));
            var languageDD = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.045f), generalLayoutGroup.RectTransform));

            foreach (string language in TextManager.AvailableLanguages)
            {
                languageDD.AddItem(TextManager.Get("Language." + language), language);
            }
            languageDD.SelectItem(TextManager.Language);
            languageDD.OnSelected = (guiComponent, obj) =>
            {
                string newLanguage = obj as string;
                if (newLanguage == Language)
                {
                    return(true);
                }

                UnsavedSettings = true;
                Language        = newLanguage;

                new GUIMessageBox(TextManager.Get("RestartRequiredLabel"), TextManager.Get("RestartRequiredLanguage"));

                return(true);
            };

            var rightPanel = new GUILayoutGroup(new RectTransform(new Vector2(0.99f - leftPanel.RectTransform.RelativeSize.X, 0.95f),
                                                                  settingsFramePadding.RectTransform, Anchor.TopLeft));

            var tabButtonHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.05f), rightPanel.RectTransform, Anchor.TopCenter), isHorizontal: true);

            var paddedFrame = new GUIFrame(new RectTransform(new Vector2(1.0f, 1.0f), rightPanel.RectTransform, Anchor.Center), style: null);


            tabs       = new GUIFrame[Enum.GetValues(typeof(Tab)).Length];
            tabButtons = new GUIButton[tabs.Length];
            foreach (Tab tab in Enum.GetValues(typeof(Tab)))
            {
                tabs[(int)tab] = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.91f), paddedFrame.RectTransform), style: "InnerFrame")
                {
                    UserData = tab
                };
                tabButtons[(int)tab] = new GUIButton(new RectTransform(new Vector2(0.25f, 1.0f), tabButtonHolder.RectTransform),
                                                     TextManager.Get("SettingsTab." + tab.ToString()), style: "GUITabButton")
                {
                    UserData  = tab,
                    OnClicked = (bt, userdata) => { SelectTab((Tab)userdata); return(true); }
                };
            }

            var buttonArea = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.08f), paddedFrame.RectTransform, Anchor.BottomCenter), style: null);

            /// Graphics tab --------------------------------------------------------------

            var leftColumn = new GUILayoutGroup(new RectTransform(new Vector2(0.46f, 0.95f), tabs[(int)Tab.Graphics].RectTransform, Anchor.TopLeft)
            {
                RelativeOffset = new Vector2(0.025f, 0.02f)
            })
            {
                RelativeSpacing = 0.01f
            };
            var rightColumn = new GUILayoutGroup(new RectTransform(new Vector2(0.46f, 0.95f), tabs[(int)Tab.Graphics].RectTransform, Anchor.TopRight)
            {
                RelativeOffset = new Vector2(0.025f, 0.02f)
            })
            {
                RelativeSpacing = 0.01f
            };

            var supportedDisplayModes = new List <DisplayMode>();

            foreach (DisplayMode mode in GraphicsAdapter.DefaultAdapter.SupportedDisplayModes)
            {
                if (supportedDisplayModes.Any(m => m.Width == mode.Width && m.Height == mode.Height))
                {
                    continue;
                }
#if OSX
                // Monogame currently doesn't support retina displays
                // so we need to disable resolutions above the viewport size.

                // In a bundled .app you just disable HiDPI in the info.plist
                // but that's probably not gonna happen.
                if (mode.Width > GameMain.Instance.GraphicsDevice.DisplayMode.Width || mode.Height > GameMain.Instance.GraphicsDevice.DisplayMode.Height)
                {
                    continue;
                }
#endif
                supportedDisplayModes.Add(mode);
            }

            new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), leftColumn.RectTransform), TextManager.Get("Resolution"));
            var resolutionDD = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.05f), leftColumn.RectTransform), elementCount: supportedDisplayModes.Count)
            {
                OnSelected = SelectResolution,
#if OSX
                ButtonEnabled = GameMain.Config.WindowMode == WindowMode.Windowed
#endif
            };

            foreach (DisplayMode mode in supportedDisplayModes)
            {
                if (mode.Width < MinSupportedResolution.X || mode.Height < MinSupportedResolution.Y)
                {
                    continue;
                }
                resolutionDD.AddItem(mode.Width + "x" + mode.Height, mode);
                if (GraphicsWidth == mode.Width && GraphicsHeight == mode.Height)
                {
                    resolutionDD.SelectItem(mode);
                }
            }

            if (resolutionDD.SelectedItemData == null)
            {
                resolutionDD.SelectItem(GraphicsAdapter.DefaultAdapter.SupportedDisplayModes.Last());
            }

            new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), leftColumn.RectTransform), TextManager.Get("DisplayMode"));
            var displayModeDD = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.05f), leftColumn.RectTransform));

            displayModeDD.AddItem(TextManager.Get("Fullscreen"), WindowMode.Fullscreen);
            displayModeDD.AddItem(TextManager.Get("Windowed"), WindowMode.Windowed);
#if (!OSX)
            displayModeDD.AddItem(TextManager.Get("BorderlessWindowed"), WindowMode.BorderlessWindowed);
            displayModeDD.SelectItem(GameMain.Config.WindowMode);
#else
            // Fullscreen option will just set itself to borderless on macOS.
            if (GameMain.Config.WindowMode == WindowMode.BorderlessWindowed)
            {
                displayModeDD.SelectItem(WindowMode.Fullscreen);
            }
            else
            {
                displayModeDD.SelectItem(GameMain.Config.WindowMode);
            }
#endif
            displayModeDD.OnSelected = (guiComponent, obj) =>
            {
                UnsavedSettings            = true;
                GameMain.Config.WindowMode = (WindowMode)guiComponent.UserData;
#if OSX
                resolutionDD.ButtonEnabled = GameMain.Config.WindowMode == WindowMode.Windowed;
#endif
                return(true);
            };

            GUITickBox vsyncTickBox = new GUITickBox(new RectTransform(new Point(32, 32), leftColumn.RectTransform), TextManager.Get("EnableVSync"))
            {
                ToolTip    = TextManager.Get("EnableVSyncToolTip"),
                OnSelected = (GUITickBox box) =>
                {
                    VSyncEnabled = box.Selected;
                    GameMain.GraphicsDeviceManager.SynchronizeWithVerticalRetrace = VSyncEnabled;
                    GameMain.GraphicsDeviceManager.ApplyChanges();
                    UnsavedSettings = true;

                    return(true);
                },
                Selected = VSyncEnabled
            };

            GUITextBlock particleLimitText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), TextManager.Get("ParticleLimit"));
            GUIScrollBar particleScrollBar = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform),
                                                              barSize: 0.1f)
            {
                UserData  = particleLimitText,
                BarScroll = (ParticleLimit - 200) / 1300.0f,
                OnMoved   = (scrollBar, scroll) =>
                {
                    ChangeSliderText(scrollBar, scroll);
                    ParticleLimit = 200 + (int)(scroll * 1300.0f);
                    return(true);
                },
                Step = 0.1f
            };
            particleScrollBar.OnMoved(particleScrollBar, particleScrollBar.BarScroll);

            new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), TextManager.Get("LosEffect"));
            var losModeDD = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform));
            losModeDD.AddItem(TextManager.Get("LosModeNone"), LosMode.None);
            losModeDD.AddItem(TextManager.Get("LosModeTransparent"), LosMode.Transparent);
            losModeDD.AddItem(TextManager.Get("LosModeOpaque"), LosMode.Opaque);
            losModeDD.SelectItem(GameMain.Config.LosMode);
            losModeDD.OnSelected = (guiComponent, obj) =>
            {
                UnsavedSettings         = true;
                GameMain.Config.LosMode = (LosMode)guiComponent.UserData;
                //don't allow changing los mode when playing as a client
                if (GameMain.Client == null)
                {
                    GameMain.LightManager.LosMode = GameMain.Config.LosMode;
                }
                return(true);
            };

            GUITextBlock LightText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), TextManager.Get("LightMapScale"))
            {
                ToolTip = TextManager.Get("LightMapScaleToolTip")
            };
            GUIScrollBar lightScrollBar = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform),
                                                           barSize: 0.1f)
            {
                UserData  = LightText,
                ToolTip   = TextManager.Get("LightMapScaleToolTip"),
                BarScroll = MathUtils.InverseLerp(0.2f, 1.0f, LightMapScale),
                OnMoved   = (scrollBar, barScroll) =>
                {
                    ChangeSliderText(scrollBar, barScroll);
                    LightMapScale   = MathHelper.Lerp(0.2f, 1.0f, barScroll);
                    UnsavedSettings = true; return(true);
                },
                Step = 0.25f
            };
            lightScrollBar.OnMoved(lightScrollBar, lightScrollBar.BarScroll);

            new GUITickBox(new RectTransform(new Point(32, 32), rightColumn.RectTransform), TextManager.Get("SpecularLighting"))
            {
                ToolTip    = TextManager.Get("SpecularLightingToolTip"),
                Selected   = SpecularityEnabled,
                OnSelected = (tickBox) =>
                {
                    SpecularityEnabled = tickBox.Selected;
                    UnsavedSettings    = true;
                    return(true);
                }
            };

            new GUITickBox(new RectTransform(new Point(32, 32), rightColumn.RectTransform), TextManager.Get("ChromaticAberration"))
            {
                ToolTip    = TextManager.Get("ChromaticAberrationToolTip"),
                Selected   = ChromaticAberrationEnabled,
                OnSelected = (tickBox) =>
                {
                    ChromaticAberrationEnabled = tickBox.Selected;
                    UnsavedSettings            = true;
                    return(true);
                }
            };

            GUITextBlock HUDScaleText      = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), TextManager.Get("HUDScale"));
            GUIScrollBar HUDScaleScrollBar = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform),
                                                              barSize: 0.1f)
            {
                UserData  = HUDScaleText,
                BarScroll = (HUDScale - MinHUDScale) / (MaxHUDScale - MinHUDScale),
                OnMoved   = (scrollBar, scroll) =>
                {
                    ChangeSliderText(scrollBar, scroll);
                    HUDScale        = MathHelper.Lerp(MinHUDScale, MaxHUDScale, scroll);
                    UnsavedSettings = true;
                    OnHUDScaleChanged?.Invoke();
                    return(true);
                },
                Step = 0.05f
            };
            HUDScaleScrollBar.OnMoved(HUDScaleScrollBar, HUDScaleScrollBar.BarScroll);

            GUITextBlock inventoryScaleText      = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), TextManager.Get("InventoryScale"));
            GUIScrollBar inventoryScaleScrollBar = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), barSize: 0.1f)
            {
                UserData  = inventoryScaleText,
                BarScroll = (InventoryScale - MinInventoryScale) / (MaxInventoryScale - MinInventoryScale),
                OnMoved   = (scrollBar, scroll) =>
                {
                    ChangeSliderText(scrollBar, scroll);
                    InventoryScale  = MathHelper.Lerp(MinInventoryScale, MaxInventoryScale, scroll);
                    UnsavedSettings = true;
                    return(true);
                },
                Step = 0.05f
            };
            inventoryScaleScrollBar.OnMoved(inventoryScaleScrollBar, inventoryScaleScrollBar.BarScroll);

            /// Audio tab ----------------------------------------------------------------

            var audioSliders = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.95f), tabs[(int)Tab.Audio].RectTransform, Anchor.TopCenter)
            {
                RelativeOffset = new Vector2(0.0f, 0.02f)
            })
            {
                RelativeSpacing = 0.01f
            };

            GUITextBlock soundVolumeText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), audioSliders.RectTransform), TextManager.Get("SoundVolume"));
            GUIScrollBar soundScrollBar  = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), audioSliders.RectTransform),
                                                            barSize: 0.05f)
            {
                UserData  = soundVolumeText,
                BarScroll = SoundVolume,
                OnMoved   = (scrollBar, scroll) =>
                {
                    ChangeSliderText(scrollBar, scroll);
                    SoundVolume = scroll;
                    return(true);
                },
                Step = 0.05f
            };
            soundScrollBar.OnMoved(soundScrollBar, soundScrollBar.BarScroll);

            GUITextBlock musicVolumeText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), audioSliders.RectTransform), TextManager.Get("MusicVolume"));
            GUIScrollBar musicScrollBar  = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), audioSliders.RectTransform),
                                                            barSize: 0.05f)
            {
                UserData  = musicVolumeText,
                BarScroll = MusicVolume,
                OnMoved   = (scrollBar, scroll) =>
                {
                    ChangeSliderText(scrollBar, scroll);
                    MusicVolume = scroll;
                    return(true);
                },
                Step = 0.05f
            };
            musicScrollBar.OnMoved(musicScrollBar, musicScrollBar.BarScroll);

            GUITextBlock voiceChatVolumeText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), audioSliders.RectTransform), TextManager.Get("VoiceChatVolume"));
            GUIScrollBar voiceChatScrollBar  = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), audioSliders.RectTransform),
                                                                barSize: 0.05f)
            {
                UserData  = voiceChatVolumeText,
                BarScroll = VoiceChatVolume,
                OnMoved   = (scrollBar, scroll) =>
                {
                    ChangeSliderText(scrollBar, scroll);
                    VoiceChatVolume = scroll;
                    return(true);
                },
                Step = 0.05f
            };
            voiceChatScrollBar.OnMoved(voiceChatScrollBar, voiceChatScrollBar.BarScroll);

            GUITickBox muteOnFocusLostBox = new GUITickBox(new RectTransform(new Point(32, 32), audioSliders.RectTransform), TextManager.Get("MuteOnFocusLost"));
            muteOnFocusLostBox.Selected   = MuteOnFocusLost;
            muteOnFocusLostBox.ToolTip    = TextManager.Get("MuteOnFocusLostToolTip");
            muteOnFocusLostBox.OnSelected = (tickBox) =>
            {
                MuteOnFocusLost = tickBox.Selected;
                UnsavedSettings = true;
                return(true);
            };

            new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), audioSliders.RectTransform), TextManager.Get("VoiceChat"));

            IList <string> deviceNames = Alc.GetString((IntPtr)null, AlcGetStringList.CaptureDeviceSpecifier);
            foreach (string name in deviceNames)
            {
                DebugConsole.NewMessage(name + " " + name.Length.ToString(), Color.Lime);
            }

            if (string.IsNullOrWhiteSpace(VoiceCaptureDevice))
            {
                VoiceCaptureDevice = deviceNames[0];
            }
#if (!OSX)
            var deviceList = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.05f), audioSliders.RectTransform), VoiceCaptureDevice, deviceNames.Count);
            foreach (string name in deviceNames)
            {
                deviceList.AddItem(name, name);
            }
            deviceList.OnSelected = (GUIComponent selected, object obj) =>
            {
                string name = obj as string;
                if (VoiceCaptureDevice == name)
                {
                    return(true);
                }

                VoipCapture.ChangeCaptureDevice(name);
                return(true);
            };
#else
            var suavemente = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), audioSliders.RectTransform), TextManager.Get("CurrentDevice") + ": " + VoiceCaptureDevice)
            {
                ToolTip       = TextManager.Get("CurrentDeviceToolTip.OSX"),
                TextAlignment = Alignment.CenterX
            };

            new GUIButton(new RectTransform(new Vector2(1.0f, 0.15f), audioSliders.RectTransform), TextManager.Get("RefreshDefaultDevice"))
            {
                ToolTip   = TextManager.Get("RefreshDefaultDeviceToolTip"),
                OnClicked = (bt, userdata) =>
                {
                    deviceNames = Alc.GetString((IntPtr)null, AlcGetStringList.CaptureDeviceSpecifier);
                    if (VoiceCaptureDevice == deviceNames[0])
                    {
                        return(true);
                    }

                    VoipCapture.ChangeCaptureDevice(deviceNames[0]);
                    suavemente.Text = TextManager.Get("CurrentDevice") + ": " + VoiceCaptureDevice;
                    suavemente.Flash(Color.Blue);

                    return(true);
                }
            };
#endif
            //var radioButtonFrame = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.12f), audioSliders.RectTransform));

            GUIRadioButtonGroup voiceMode = new GUIRadioButtonGroup();
            for (int i = 0; i < 3; i++)
            {
                string langStr = "VoiceMode." + ((VoiceMode)i).ToString();
                var    tick    = new GUITickBox(new RectTransform(new Point(32, 32), audioSliders.RectTransform), TextManager.Get(langStr))
                {
                    ToolTip = TextManager.Get(langStr + "ToolTip")
                };

                voiceMode.AddRadioButton((VoiceMode)i, tick);
            }

            var micVolumeText   = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), audioSliders.RectTransform), TextManager.Get("MicrophoneVolume"));
            var micVolumeSlider = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), audioSliders.RectTransform),
                                                   barSize: 0.05f)
            {
                UserData  = micVolumeText,
                BarScroll = (float)Math.Sqrt(MathUtils.InverseLerp(0.2f, 5.0f, MicrophoneVolume)),
                OnMoved   = (scrollBar, scroll) =>
                {
                    MicrophoneVolume = MathHelper.Lerp(0.2f, 5.0f, scroll * scroll);
                    MicrophoneVolume = (float)Math.Round(MicrophoneVolume, 1);
                    ChangeSliderText(scrollBar, MicrophoneVolume);
                    scrollBar.Step = 0.05f;
                    return(true);
                },
                Step = 0.05f
            };
            micVolumeSlider.OnMoved(micVolumeSlider, micVolumeSlider.BarScroll);


            var extraVoiceSettingsContainer = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.2f), audioSliders.RectTransform, Anchor.BottomCenter), style: null);

            var voiceInputContainer = new GUILayoutGroup(new RectTransform(Vector2.One, extraVoiceSettingsContainer.RectTransform, Anchor.BottomCenter));
            new GUITextBlock(new RectTransform(new Vector2(0.6f, 0.25f), voiceInputContainer.RectTransform), TextManager.Get("InputType.Voice") + ": ");
            var voiceKeyBox = new GUITextBox(new RectTransform(new Vector2(0.4f, 0.25f), voiceInputContainer.RectTransform, Anchor.TopRight),
                                             text: keyMapping[(int)InputType.Voice].ToString())
            {
                UserData = InputType.Voice
            };
            voiceKeyBox.OnSelected   += KeyBoxSelected;
            voiceKeyBox.SelectedColor = Color.Gold * 0.3f;

            var          voiceActivityGroup = new GUILayoutGroup(new RectTransform(Vector2.One, extraVoiceSettingsContainer.RectTransform));
            GUITextBlock noiseGateText      = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.25f), voiceActivityGroup.RectTransform), TextManager.Get("NoiseGateThreshold"))
            {
                TextGetter = () =>
                {
                    return(TextManager.Get("NoiseGateThreshold") + " " + ((int)NoiseGateThreshold).ToString() + " dB");
                }
            };
            var dbMeter = new GUIProgressBar(new RectTransform(new Vector2(1.0f, 0.25f), voiceActivityGroup.RectTransform), 0.0f, Color.Lime);
            dbMeter.ProgressGetter = () =>
            {
                if (VoipCapture.Instance == null)
                {
                    return(0.0f);
                }
                dbMeter.Color = VoipCapture.Instance.LastdB > NoiseGateThreshold ? Color.Lime : Color.Orange; //TODO: i'm a filthy hack
                return(((float)VoipCapture.Instance.LastdB + 100.0f) / 100.0f);
            };
            var noiseGateSlider = new GUIScrollBar(new RectTransform(Vector2.One, dbMeter.RectTransform, Anchor.Center), color: Color.White, barSize: 0.03f);
            noiseGateSlider.Frame.Visible  = false;
            noiseGateSlider.Step           = 0.01f;
            noiseGateSlider.Range          = new Vector2(-100.0f, 0.0f);
            noiseGateSlider.BarScrollValue = NoiseGateThreshold;
            noiseGateSlider.OnMoved        = (GUIScrollBar scrollBar, float barScroll) =>
            {
                NoiseGateThreshold = scrollBar.BarScrollValue;
                UnsavedSettings    = true;
                return(true);
            };

            voiceMode.OnSelect = (GUIRadioButtonGroup rbg, Enum value) =>
            {
                if (rbg.Selected != null && rbg.Selected.Equals(value))
                {
                    return;
                }
                try
                {
                    VoiceMode vMode = (VoiceMode)value;
                    VoiceSetting = vMode;
                    if (vMode == VoiceMode.Activity)
                    {
                        voiceActivityGroup.Visible = true;
                        if (GameMain.Client == null && VoipCapture.Instance == null)
                        {
                            VoipCapture.Create(GameMain.Config.VoiceCaptureDevice);
                            if (VoipCapture.Instance == null)
                            {
                                VoiceSetting = vMode = VoiceMode.Disabled;
                                voiceInputContainer.Visible = false;
                                voiceActivityGroup.Visible  = false;
                                return;
                            }
                        }
                    }
                    else
                    {
                        voiceActivityGroup.Visible = false;
                        if (GameMain.Client == null)
                        {
                            VoipCapture.Instance?.Dispose();
                        }
                    }

                    voiceInputContainer.Visible = (vMode == VoiceMode.PushToTalk);
                    UnsavedSettings             = true;
                }
                catch (Exception e)
                {
                    DebugConsole.ThrowError("Failed to set voice capture mode.", e);
                    GameAnalyticsManager.AddErrorEventOnce("SetVoiceCaptureMode", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, "Failed to set voice capture mode. " + e.Message + "\n" + e.StackTrace);
                    VoiceSetting = VoiceMode.Disabled;
                }
            };
            voiceMode.Selected = VoiceSetting;

            /// Controls tab -------------------------------------------------------------
            var controlsLayoutGroup = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.95f), tabs[(int)Tab.Controls].RectTransform, Anchor.TopCenter)
            {
                RelativeOffset = new Vector2(0.0f, 0.02f)
            })
            {
                RelativeSpacing = 0.01f
            };

            GUITextBlock aimAssistText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), controlsLayoutGroup.RectTransform), TextManager.Get("AimAssist"))
            {
                ToolTip = TextManager.Get("AimAssistToolTip")
            };
            GUIScrollBar aimAssistSlider = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), controlsLayoutGroup.RectTransform),
                                                            barSize: 0.05f)
            {
                UserData  = aimAssistText,
                BarScroll = MathUtils.InverseLerp(0.0f, 5.0f, AimAssistAmount),
                ToolTip   = TextManager.Get("AimAssistToolTip"),
                OnMoved   = (scrollBar, scroll) =>
                {
                    ChangeSliderText(scrollBar, scroll);
                    AimAssistAmount = MathHelper.Lerp(0.0f, 5.0f, scroll);
                    return(true);
                },
                Step = 0.1f
            };
            aimAssistSlider.OnMoved(aimAssistSlider, aimAssistSlider.BarScroll);

            new GUITickBox(new RectTransform(new Point(32, 32), controlsLayoutGroup.RectTransform), TextManager.Get("EnableMouseLook"))
            {
                ToolTip    = TextManager.Get("EnableMouseLookToolTip"),
                Selected   = EnableMouseLook,
                OnSelected = (tickBox) =>
                {
                    EnableMouseLook = tickBox.Selected;
                    UnsavedSettings = true;
                    return(true);
                }
            };

            var inputFrame = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.75f), controlsLayoutGroup.RectTransform), isHorizontal: true)
            {
                Stretch = true, RelativeSpacing = 0.03f
            };

            var inputColumnLeft = new GUILayoutGroup(new RectTransform(new Vector2(0.5f, 1.0f), inputFrame.RectTransform))
            {
                Stretch = true, RelativeSpacing = 0.02f
            };
            var inputColumnRight = new GUILayoutGroup(new RectTransform(new Vector2(0.5f, 1.0f), inputFrame.RectTransform))
            {
                Stretch = true, RelativeSpacing = 0.02f
            };

            var inputNames = Enum.GetValues(typeof(InputType));
            for (int i = 0; i < inputNames.Length; i++)
            {
                var inputContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.06f), (i <= (inputNames.Length / 2.2f) ? inputColumnLeft : inputColumnRight).RectTransform))
                {
                    Stretch = true, IsHorizontal = true, RelativeSpacing = 0.05f, Color = new Color(12, 14, 15, 215)
                };
                new GUITextBlock(new RectTransform(new Vector2(0.3f, 1.0f), inputContainer.RectTransform, Anchor.TopLeft)
                {
                    MinSize = new Point(150, 0)
                },
                                 TextManager.Get("InputType." + ((InputType)i)) + ": ", font: GUI.SmallFont)
                {
                    ForceUpperCase = true
                };
                var keyBox = new GUITextBox(new RectTransform(new Vector2(0.7f, 1.0f), inputContainer.RectTransform),
                                            text: keyMapping[i].ToString(), font: GUI.SmallFont)
                {
                    UserData = i
                };
                keyBox.OnSelected   += KeyBoxSelected;
                keyBox.SelectedColor = Color.Gold * 0.3f;
            }

            var resetControlsHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.07f), controlsLayoutGroup.RectTransform), isHorizontal: true)
            {
                RelativeSpacing = 0.02f
            };

            new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), resetControlsHolder.RectTransform), TextManager.Get("SetDefaultBindings"))
            {
                ToolTip   = TextManager.Get("SetDefaultBindingsToolTip"),
                OnClicked = (button, data) =>
                {
                    ResetControls(legacy: false);
                    return(true);
                }
            };

            new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), resetControlsHolder.RectTransform), TextManager.Get("SetLegacyBindings"))
            {
                ToolTip   = TextManager.Get("SetLegacyBindingsToolTip"),
                OnClicked = (button, data) =>
                {
                    ResetControls(legacy: true);
                    return(true);
                }
            };

            //spacing
            new GUIFrame(new RectTransform(new Vector2(1.0f, 0.02f), generalLayoutGroup.RectTransform), style: null);

            new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), buttonArea.RectTransform, Anchor.BottomLeft),
                          TextManager.Get("Cancel"), style: "GUIButtonLarge")
            {
                IgnoreLayoutGroups = true,
                OnClicked          = (x, y) =>
                {
                    if (UnsavedSettings)
                    {
                        LoadPlayerConfig();
                    }
                    if (Screen.Selected == GameMain.MainMenuScreen)
                    {
                        GameMain.MainMenuScreen.ReturnToMainMenu(null, null);
                    }
                    GUI.SettingsMenuOpen = false;
                    return(true);
                }
            };

            new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), buttonArea.RectTransform, Anchor.BottomCenter),
                          TextManager.Get("Reset"), style: "GUIButtonLarge")
            {
                IgnoreLayoutGroups = true,
                OnClicked          = (button, data) =>
                {
                    // TODO: add a prompt
                    LoadDefaultConfig();
                    CheckBindings(true);
                    RefreshItemMessages();
                    ApplySettings();
                    if (Screen.Selected == GameMain.MainMenuScreen)
                    {
                        GameMain.MainMenuScreen.ResetSettingsFrame(currentTab);
                    }
                    else
                    {
                        ResetSettingsFrame();
                        CreateSettingsFrame(currentTab);
                    }
                    return(true);
                }
            };

            applyButton = new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), buttonArea.RectTransform, Anchor.BottomRight),
                                        TextManager.Get("ApplySettingsButton"), style: "GUIButtonLarge")
            {
                IgnoreLayoutGroups = true,
                Enabled            = false
            };
            applyButton.OnClicked = ApplyClicked;

            UnsavedSettings = false; // Reset unsaved settings to false once the UI has been created
            SelectTab(selectedTab);
        }
Ejemplo n.º 19
0
        void initAudio()
        {
            IntPtr         nullDevice = System.IntPtr.Zero;
            IList <string> allDevices = Alc.GetString(nullDevice, AlcGetStringList.DeviceSpecifier);

            foreach (string s in allDevices)
            {
                Console.WriteLine("OpenAL device " + s);
            }

            // Open preferred device
            ContextHandle alContext;
            IntPtr        ALDevicePtr = Alc.OpenDevice(null);

            if (ALDevicePtr != null)
            {
                int[] deviceAttributes = null;
                alContext = Alc.CreateContext(ALDevicePtr, deviceAttributes);
                Alc.MakeContextCurrent(alContext);
            }
            else
            {
                Console.WriteLine("Could not get AL device");
                return;
            }

            string alRenderer = AL.Get(ALGetString.Renderer);
            string alVendor   = AL.Get(ALGetString.Vendor);
            string alVersion  = AL.Get(ALGetString.Version);

            Console.WriteLine("OpenAL Renderer {0}  Vendor {1}  Version {2}", alRenderer, alVendor, alVersion);


            Error.checkALError("initAudio");
            int alBuffer = AL.GenBuffer();

            Error.checkALError("initAudio genBuffer");


            int frequenzy = 44100;

            // Buffer data
            bool dataisVorbis = false;

            string vorbisEXTName = "AL_EXT_vorbis";

            if (AL.IsExtensionPresent(vorbisEXTName) && dataisVorbis)
            {
                Console.WriteLine("AL can use vorbis");
                IntPtr vorbisBuffer = System.IntPtr.Zero;
                int    vorbisSize   = 0;
                AL.BufferData(alBuffer, ALFormat.VorbisExt, vorbisBuffer, vorbisSize, frequenzy);
            }
            else
            {
                // Load wav

                FileStream audioFile     = File.Open("../data/music/bosca.wav", FileMode.Open, FileAccess.Read);
                long       wavSize       = audioFile.Length;
                byte[]     audioContents = new byte[wavSize];

                audioFile.Read(audioContents, 0, (int)wavSize);
                IntPtr wavBuffer = Marshal.AllocHGlobal(audioContents.Length);
                Marshal.Copy(audioContents, 0, wavBuffer, audioContents.Length);

                AL.BufferData(alBuffer, ALFormat.Stereo16, wavBuffer, (int)wavSize, frequenzy);
                Marshal.FreeHGlobal(wavBuffer);
                audioFile.Close();
            }

            Error.checkALError("initAudio bufferAudio");

            int alSource = AL.GenSource();

            Error.checkALError("initAudio genSource");

            // Attach buffer to source.
            AL.Source(alSource, ALSourcei.Buffer, alBuffer);

            // Set listener and source to same place
            Vector3 listenerPos = new Vector3(0, 0, 0);
            Vector3 sourcePos   = new Vector3(0, 0, 0);

            AL.Listener(ALListener3f.Position, ref listenerPos);
            AL.Source(alSource, ALSource3f.Position, ref sourcePos);

            // Play buffer
            AL.SourcePlay(alSource);
        }
Ejemplo n.º 20
0
        /// \internal
        /// <summary>Creates the audio context using the specified device.</summary>
        /// <param name="device">The device descriptor obtained through AudioContext.AvailableDevices, or null for the default device.</param>
        /// <param name="freq">Frequency for mixing output buffer, in units of Hz. Pass 0 for driver default.</param>
        /// <param name="refresh">Refresh intervals, in units of Hz. Pass 0 for driver default.</param>
        /// <param name="sync">Flag, indicating a synchronous context.</param>
        /// <param name="enableEfx">Indicates whether the EFX extension should be initialized, if present.</param>
        /// <param name="efxAuxiliarySends">Requires EFX enabled. The number of desired Auxiliary Sends per source.</param>
        /// <exception cref="ArgumentOutOfRangeException">Occurs when a specified parameter is invalid.</exception>
        /// <exception cref="AudioDeviceException">
        /// Occurs when the specified device is not available, or is in use by another program.
        /// </exception>
        /// <exception cref="AudioContextException">
        /// Occurs when an audio context could not be created with the specified parameters.
        /// </exception>
        /// <exception cref="NotSupportedException">
        /// Occurs when an AudioContext already exists.</exception>
        /// <remarks>
        /// <para>For maximum compatibility, you are strongly recommended to use the default constructor.</para>
        /// <para>Multiple AudioContexts are not supported at this point.</para>
        /// <para>
        /// The number of auxilliary EFX sends depends on the audio hardware and drivers. Most Realtek devices, as well
        /// as the Creative SB Live!, support 1 auxilliary send. Creative's Audigy and X-Fi series support 4 sends.
        /// Values higher than supported will be clamped by the driver.
        /// </para>
        /// </remarks>
        private void CreateContext(string device, int freq, int refresh, bool sync, bool enableEfx, MaxAuxiliarySends efxAuxiliarySends)
        {
            if (!AudioDeviceEnumerator.IsOpenALSupported)
            {
                throw new DllNotFoundException("openal32.dll");
            }

            if (AudioDeviceEnumerator.Version == AudioDeviceEnumerator.AlcVersion.Alc1_1 && AudioDeviceEnumerator.AvailablePlaybackDevices.Count == 0)    // Alc 1.0 does not support device enumeration.
            {
                throw new NotSupportedException("No audio hardware is available.");
            }
            if (context_exists)
            {
                throw new NotSupportedException("Multiple AudioContexts are not supported.");
            }
            if (freq < 0)
            {
                throw new ArgumentOutOfRangeException("freq", freq, "Should be greater than zero.");
            }
            if (refresh < 0)
            {
                throw new ArgumentOutOfRangeException("refresh", refresh, "Should be greater than zero.");
            }


            if (!String.IsNullOrEmpty(device))
            {
                device_name = device;
                Device      = Alc.OpenDevice(device); // try to open device by name
            }
            if (Device == IntPtr.Zero)
            {
                device_name = "IntPtr.Zero (null string)";
                Device      = Alc.OpenDevice(null); // try to open unnamed default device
            }
            if (Device == IntPtr.Zero)
            {
                device_name = AudioContext.DefaultDevice;
                Device      = Alc.OpenDevice(AudioContext.DefaultDevice); // try to open named default device
            }
            if (Device == IntPtr.Zero)
            {
                device_name = "None";
                throw new AudioDeviceException(String.Format("Audio device '{0}' does not exist or is tied up by another application.",
                                                             String.IsNullOrEmpty(device) ? "default" : device));
            }

            CheckErrors();

            // Build the attribute list
            List <int> attributes = new List <int>();

            if (freq != 0)
            {
                attributes.Add((int)AlcContextAttributes.Frequency);
                attributes.Add(freq);
            }

            if (refresh != 0)
            {
                attributes.Add((int)AlcContextAttributes.Refresh);
                attributes.Add(refresh);
            }

            attributes.Add((int)AlcContextAttributes.Sync);
            attributes.Add(sync ? 1 : 0);

            if (enableEfx && Alc.IsExtensionPresent(Device, "ALC_EXT_EFX"))
            {
                int num_slots;
                switch (efxAuxiliarySends)
                {
                case MaxAuxiliarySends.One:
                case MaxAuxiliarySends.Two:
                case MaxAuxiliarySends.Three:
                case MaxAuxiliarySends.Four:
                    num_slots = (int)efxAuxiliarySends;
                    break;

                default:
                case MaxAuxiliarySends.UseDriverDefault:
                    Alc.GetInteger(Device, AlcGetInteger.EfxMaxAuxiliarySends, 1, out num_slots);
                    break;
                }

                attributes.Add((int)AlcContextAttributes.EfxMaxAuxiliarySends);
                attributes.Add(num_slots);
            }
            attributes.Add(0);

            context_handle = Alc.CreateContext(Device, attributes.ToArray());

            if (context_handle == ContextHandle.Zero)
            {
                Alc.CloseDevice(Device);
                throw new AudioContextException("The audio context could not be created with the specified parameters.");
            }

            CheckErrors();

            // HACK: OpenAL SI on Linux/ALSA crashes on MakeCurrent. This hack avoids calling MakeCurrent when
            // an old OpenAL version is detect - it may affect outdated OpenAL versions different than OpenAL SI,
            // but it looks like a good compromise for now.
            if (AudioDeviceEnumerator.AvailablePlaybackDevices.Count > 0)
            {
                MakeCurrent();
            }

            CheckErrors();

            device_name = Alc.GetString(Device, AlcGetString.DeviceSpecifier);


            lock (audio_context_lock)
            {
                available_contexts.Add(this.context_handle, this);
                context_exists = true;
            }
        }
Ejemplo n.º 21
0
        // --- initialization and deinitialization ---

        /// <summary>Initializes audio. A call to Deinitialize must be made when terminating the program.</summary>
        /// <returns>Whether initializing audio was successful.</returns>
        public void Initialize(HostInterface host, SoundRange range)
        {
            if (host.Platform == HostPlatform.MicrosoftWindows)
            {
                /*
                 *  If shipping an AnyCPU build and OpenALSoft / SDL, these are architecture specific PInvokes
                 *  Add the appropriate search path so this will work (common convention)
                 */
                string path = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
                if (path != null)
                {
                    path = Path.Combine(path, IntPtr.Size == 4 ? "x86" : "x64");
                    bool ok = SetDllDirectory(path);
                    if (!ok)
                    {
                        throw new System.ComponentModel.Win32Exception();
                    }
                }
            }
            Deinitialize();

            CurrentHost = host;

            switch (range)
            {
            case SoundRange.Low:
                OuterRadiusFactorMinimum      = 2.0;
                OuterRadiusFactorMaximum      = 8.0;
                OuterRadiusFactorMaximumSpeed = 1.0;
                break;

            case SoundRange.Medium:
                OuterRadiusFactorMinimum      = 4.0;
                OuterRadiusFactorMaximum      = 16.0;
                OuterRadiusFactorMaximumSpeed = 2.0;
                break;

            case SoundRange.High:
                OuterRadiusFactorMinimum      = 6.0;
                OuterRadiusFactorMaximum      = 24.0;
                OuterRadiusFactorMaximumSpeed = 3.0;
                break;
            }
            OuterRadiusFactor      = Math.Sqrt(OuterRadiusFactorMinimum * OuterRadiusFactorMaximum);
            OuterRadiusFactorSpeed = 0.0;
            OpenAlDevice           = Alc.OpenDevice(null);
            string deviceName = Alc.GetString(OpenAlDevice, AlcGetString.DefaultDeviceSpecifier);

            if ((Environment.OSVersion.Platform == PlatformID.Win32S | Environment.OSVersion.Platform == PlatformID.Win32Windows | Environment.OSVersion.Platform == PlatformID.Win32NT) && deviceName == "Generic Software")
            {
                /*
                 * Creative OpenAL implementation on Windows seems to be limited to max 16 simulataneous sounds
                 * Now shipping OpenAL Soft, but detect this and don't glitch
                 * Further note that the current version of OpenAL Soft (1.20.0 at the time of writing) does not like OpenTK
                 * The version in use is 1.17.0 found here: https://openal-soft.org/openal-binaries/
                 */
                systemMaxSounds = 16;
            }
            try
            {
                OpenAlMic = new AudioCapture(AudioCapture.DefaultDevice, SamplingRate, ALFormat.Mono16, BufferSize);
            }
            catch
            {
                OpenAlMic = null;
            }

            if (OpenAlDevice != IntPtr.Zero)
            {
                OpenAlContext = Alc.CreateContext(OpenAlDevice, (int[])null);
                if (OpenAlContext != ContextHandle.Zero)
                {
                    Alc.MakeContextCurrent(OpenAlContext);
                    try
                    {
                        AL.SpeedOfSound(343.0f);
                    }
                    catch
                    {
                        MessageBox.Show(Translations.GetInterfaceString("errors_sound_openal_version"), Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                    AL.DistanceModel(ALDistanceModel.None);
                    return;
                }
                Alc.CloseDevice(OpenAlDevice);
                OpenAlDevice = IntPtr.Zero;
                if (OpenAlMic != null)
                {
                    OpenAlMic.Dispose();
                    OpenAlMic = null;
                }
                MessageBox.Show(Translations.GetInterfaceString("errors_sound_openal_context"), Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            OpenAlContext = ContextHandle.Zero;
            MessageBox.Show(Translations.GetInterfaceString("errors_sound_openal_device"), Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
        }
Ejemplo n.º 22
0
        internal void CheckError()
        {
            var code = Alc.GetError(Handle);

            if (code == AlcError.NoError)
            {
                return;
            }
            throw new Exception("OpenAL error with device '" + deviceName + "' (" + code + "): " + Alc.GetString(IntPtr.Zero, (AlcGetString)code));
        }
Ejemplo n.º 23
0
        public SoundManager()
        {
            loadedSounds      = new List <Sound>();
            streamingThread   = null;
            categoryModifiers = null;

            int alcError = Alc.NoError;

            string deviceName = Alc.GetString(IntPtr.Zero, Alc.DefaultDeviceSpecifier);

            DebugConsole.NewMessage($"Attempting to open ALC device \"{deviceName}\"");

            alcDevice = IntPtr.Zero;
            for (int i = 0; i < 3; i++)
            {
                alcDevice = Alc.OpenDevice(deviceName);
                if (alcDevice == IntPtr.Zero)
                {
                    DebugConsole.NewMessage($"ALC device initialization attempt #{i + 1} failed: device is null");
                }
                else
                {
                    alcError = Alc.GetError(alcDevice);
                    if (alcError != Alc.NoError)
                    {
                        DebugConsole.NewMessage($"ALC device initialization attempt #{i + 1} failed: error code {Alc.GetErrorString(alcError)}");
                        bool closed = Alc.CloseDevice(alcDevice);
                        if (!closed)
                        {
                            DebugConsole.NewMessage($"Failed to close ALC device");
                        }
                        alcDevice = IntPtr.Zero;
                    }
                }
            }
            if (alcDevice == IntPtr.Zero)
            {
                DebugConsole.ThrowError("ALC device creation failed too many times!");
                Disabled = true;
                return;
            }

            int[] alcContextAttrs = new int[] { };
            alcContext = Alc.CreateContext(alcDevice, alcContextAttrs);
            if (alcContext == null)
            {
                DebugConsole.ThrowError("Failed to create an ALC context! (error code: " + Alc.GetError(alcDevice).ToString() + "). Disabling audio playback...");
                Disabled = true;
                return;
            }

            if (!Alc.MakeContextCurrent(alcContext))
            {
                DebugConsole.ThrowError("Failed to assign the current ALC context! (error code: " + Alc.GetError(alcDevice).ToString() + "). Disabling audio playback...");
                Disabled = true;
                return;
            }

            alcError = Alc.GetError(alcDevice);
            if (alcError != Alc.NoError)
            {
                DebugConsole.ThrowError("Error after assigning ALC context: " + Alc.GetErrorString(alcError) + ". Disabling audio playback...");
                Disabled = true;
                return;
            }

            sourcePools = new SoundSourcePool[2];
            sourcePools[(int)SourcePoolIndex.Default]     = new SoundSourcePool(SOURCE_COUNT);
            playingChannels[(int)SourcePoolIndex.Default] = new SoundChannel[SOURCE_COUNT];

            sourcePools[(int)SourcePoolIndex.Voice]     = new SoundSourcePool(16);
            playingChannels[(int)SourcePoolIndex.Voice] = new SoundChannel[16];

            Al.DistanceModel(Al.LinearDistanceClamped);

            int alError = Al.GetError();

            if (alError != Al.NoError)
            {
                DebugConsole.ThrowError("Error setting distance model: " + Al.GetErrorString(alError) + ". Disabling audio playback...");
                Disabled = true;
                return;
            }

            ListenerPosition     = Vector3.Zero;
            ListenerTargetVector = new Vector3(0.0f, 0.0f, 1.0f);
            ListenerUpVector     = new Vector3(0.0f, -1.0f, 0.0f);

            CompressionDynamicRangeGain = 1.0f;
        }
Ejemplo n.º 24
0
        public static void AlcUnitTestFunc()
        {
            AudioContext context = new AudioContext();

            Trace.WriteLine("Testing AudioContext functions.");
            Trace.Indent();

//            Trace.WriteLine("Suspend()...");
//            context.Suspend();
//            Trace.Assert(!context.IsProcessing);
//
//            Trace.WriteLine("Process()...");
//            context.Process();
//            Trace.Assert(context.IsProcessing);

            //Trace.WriteLine("MakeCurrent()...");
            //context.MakeCurrent();
            //Trace.Assert(context.IsCurrent);

            //Trace.WriteLine("IsCurrent = false...");
            //context.IsCurrent = false;
            //Trace.Assert(!context.IsCurrent);

            //Trace.WriteLine("IsCurrent = true...");
            //context.IsCurrent = true;
            //Trace.Assert(context.IsCurrent);

            Trace.WriteLine("AudioContext.CurrentContext...");
            Trace.Assert(AudioContext.CurrentContext == context);

            #region Get Attribs

            //int AttribCount;
            //Alc.GetInteger(context.Device, AlcGetInteger.AttributesSize, sizeof(int), out AttribCount);
            //Trace.WriteLine("AttributeSize: " + AttribCount);

            //if (AttribCount > 0)
            //{
            //    int[] Attribs = new int[AttribCount];
            //    Alc.GetInteger(context.Device, AlcGetInteger.AllAttributes, AttribCount, out Attribs[0]);
            //    for (int i = 0; i < Attribs.Length; i++)
            //    {
            //        Trace.Write(Attribs[i]);
            //        Trace.Write(" ");
            //    }
            //    Trace.WriteLine();
            //}

            #endregion Get Attribs

#if false
            AlDevice  MyDevice;
            AlContext MyContext;

            // Initialize Open AL
            MyDevice = Alc.OpenDevice(null);  // open default device
            if (MyDevice != Al.Null)
            {
                Trace.WriteLine("Device allocation succeeded.");
                MyContext = Alc.CreateContext(MyDevice, Al.Null);   // create context
                if (MyContext != Al.Null)
                {
                    Trace.WriteLine("Context allocation succeeded.");
                    GetOpenALErrors(MyDevice);

                    Alc.SuspendContext(MyContext);                      // disable context
                    Alc.ProcessContext(MyContext);                      // enable context. The default state of a context created by alcCreateContext is that it is processing.
                    Al.Bool result = Alc.MakeContextCurrent(MyContext); // set active context
                    Trace.WriteLine("MakeContextCurrent succeeded? " + result);
                    GetOpenALErrors(MyDevice);

                    Trace.WriteLine("Default: " + Alc.GetString(MyDevice, Enums.AlcGetString.DefaultDeviceSpecifier));
                    Trace.WriteLine("Device: " + Alc.GetString(MyDevice, Enums.AlcGetString.DeviceSpecifier));
                    Trace.WriteLine("Extensions: " + Alc.GetString(MyDevice, Enums.AlcGetString.Extensions));
                    GetOpenALErrors(MyDevice);

                    #region Get Attribs
                    int AttribCount;
                    Alc.GetInteger(MyDevice, Enums.AlcGetInteger.AttributesSize, sizeof(int), out AttribCount);
                    Trace.WriteLine("AttributeSize: " + AttribCount);

                    if (AttribCount > 0)
                    {
                        int[] Attribs = new int[AttribCount];
                        Alc.GetInteger(MyDevice, Enums.AlcGetInteger.AttributesSize, AttribCount, out Attribs[0]);
                        for (int i = 0; i < Attribs.Length; i++)
                        {
                            Trace.Write(", " + Attribs[i]);
                        }
                        Trace.WriteLine( );
                    }
                    #endregion Get Attribs
                    GetOpenALErrors(MyDevice);

                    AlDevice  currdev = Alc.GetContextsDevice(MyContext);
                    AlContext currcon = Alc.GetCurrentContext( );

                    if (MyDevice == currdev)
                    {
                        Trace.WriteLine("Devices match.");
                    }
                    else
                    {
                        Trace.WriteLine("Error: Devices do not match.");
                    }

                    if (MyContext == currcon)
                    {
                        Trace.WriteLine("Context match.");
                    }
                    else
                    {
                        Trace.WriteLine("Error: Contexts do not match.");
                    }

                    // exit
                    Alc.MakeContextCurrent(Al.Null);   // results in no context being current
                    Alc.DestroyContext(MyContext);
                    result = Alc.CloseDevice(MyDevice);
                    Trace.WriteLine("Result: " + result);
                    Trace.ReadLine( );
                }
                else
                {
                    Trace.WriteLine("Context creation failed.");
                }
            }
            else
            {
                Trace.WriteLine("Failed to find suitable Device.");
            }
#endif

            /*
             * include <stdlib.h>
             * include <AL/alut.h>
             *
             * int
             * main (int argc, char **argv)
             * {
             * ALuint helloBuffer, helloSource;
             * alutInit (&argc, argv);
             * helloBuffer = alutCreateBufferHelloWorld ();  alGenSources (1, &helloSource);
             * alSourcei (helloSource, AL_Buffer, helloBuffer);
             * alSourcePlay (helloSource);
             * alutSleep (1);
             * alutExit ();
             * return EXIT_SUCCESS;
             * }*/

            /*
             *
             * Processing Loop Example:
             * // PlaceCamera - places OpenGL camera & updates OpenAL listener buffer
             * void AVEnvironment::PlaceCamera()
             * {
             * // update OpenGL camera position
             * glMatrixMode(GL_PROJECTION);
             * glLoadIdentity();
             * glFrustum(-0.1333, 0.1333, -0.1, 0.1, 0.2, 50.0);
             * gluLookAt(listenerPos[0], listenerPos[1], listenerPos[2],
             * (listenerPos[0] + sin(listenerAngle)), listenerPos[1],
             * (listenerPos[2] - cos(listenerAngle)),
             * 0.0, 1.0, 0.0);
             * // update OpenAL
             * // place listener at camera
             * alListener3f(AL_POSITION, listenerPos[0], listenerPos[1], listenerPos[2]);
             * float directionvect[6];
             * directionvect[0] = (float) sin(listenerAngle);
             * directionvect[1] = 0;
             * directionvect[2] = (float) cos(listenerAngle);
             * directionvect[3] = 0;
             * directionvect[4] = 1;
             * directionvect[5] = 0;
             * alListenerfv(AL_ORIENTATION, directionvect);
             * }
             *
             */
        }
Ejemplo n.º 25
0
        protected bool init()
        {
            if (myIsInitialized == true)
            {
                return(true);
            }


            Info.print("------------------AUDIO MANAGER----------------");

            try
            {
                //try to get the DirectSound default (openAL-soft's target)
                string defaultDevice = AudioContext.DefaultDevice;
                myContext = new AudioContext(defaultDevice);
            }
            catch (AudioException ex)
            {
                Error.print("Exception trying to initialize OpenAL Context.  Verify OpenAL drivers are installed");
                Error.print("Exception: {0}", ex.Message);
                if (ex.InnerException != null)
                {
                    Error.print("Inner Exception: {0}", ex.InnerException.Message);
                }

                return(false);
            }

            //make the context current
            myContext.MakeCurrent();
            myContext.CheckErrors();
            myDevice = Alc.GetContextsDevice(Alc.GetCurrentContext());

            //print out the attributs
            int attributeSize = 0;

            Alc.GetInteger(myDevice, AlcGetInteger.AttributesSize, 1, out attributeSize);
            int[] attBuffer = new int[attributeSize * 2 + 1];
            Alc.GetInteger(myDevice, AlcGetInteger.AllAttributes, attributeSize * 2 + 1, attBuffer);
            int idx = 0;

            while (attBuffer[idx] != 0)
            {
                Info.print(String.Format("Context attribute: {0}:{1}", Audio.enumToString(attBuffer[idx]), attBuffer[idx + 1]));
                idx += 2;
            }

            //print some debug information about the system
            string alExtensions  = AL.Get(ALGetString.Extensions);
            string alcExtensions = Alc.GetString(myDevice, AlcGetString.Extensions);

            Info.print("Opened Audio device {0}", myContext.ToString());
            Info.print("OpenAL Vendor: {0}", AL.Get(ALGetString.Vendor));
            Info.print("OpenAL Version: {0}", AL.Get(ALGetString.Version));
            Info.print("OpenAL Renderer: {0}", AL.Get(ALGetString.Renderer));
            Info.print("OpenAL Extensions: {0}", AL.Get(ALGetString.Extensions));
            Info.print("OpenAL Context Extensions: {0} ", Alc.GetString(myDevice, AlcGetString.Extensions));



            string[] extensions = alcExtensions.Split(' ');
            for (int i = 0; i < extensions.Length; i++)
            {
                if (extensions[i] == "ALC_EXT_EFX")
                {
                    myEnvironmentalProcessingAvailable = true;
                }
            }

            Info.print("Environmental Processing: " + (myEnvironmentalProcessingAvailable ? "available" : "unavailable"));

            createVoices(myMaxVoices);

            Info.print("------------------AUDIO MANAGER----------------");

            return(true);
        }
Ejemplo n.º 26
0
 public AudioCapture(int frequency, int channels, float duration) : this(Alc.GetString(IntPtr.Zero, AlcGetString.CaptureDefaultDeviceSpecifier), frequency, channels, duration)
 {
 }
Ejemplo n.º 27
0
 public AudioHandler(Dictionary <string, string> WavDefinitions, string DeviceName = null)
 {
     Devices = Alc.GetString((IntPtr)null, AlcGetStringList.AllDevicesSpecifier).ToList();
     ChangeAudioDevice(DeviceName);
     this.AudioData = WavDefinitions.AsParallel().ToDictionary(x => x.Key, x => new AudioData(x.Key, x.Value));
 }
Ejemplo n.º 28
0
        static async Task Main(string[] args)
        {
            // =============================================================================================================
            // inspired by: https://stackoverflow.com/questions/4087727/openal-how-to-create-simple-microphone-echo-programm

            string captureDeviceSpecifier = Alc.GetString(IntPtr.Zero, Alc.CaptureDeviceSpecifier);

            Console.WriteLine("Capture device name: " + captureDeviceSpecifier);

            //var audioDevice = Alc.OpenDevice(null);

            ////var errorCode = Alc.GetError(audioDevice); // TODO: check this after each Alc call
            ////var errorCode = Al.GetError(); // TODO: check this after each Al call

            //var context = Alc.CreateContext(audioDevice, null);
            //Alc.MakeContextCurrent(context);

            const int frequency     = 44100;
            const int keywordLength = (int)(frequency);

            var captureDevice = Alc.CaptureOpenDevice(captureDeviceSpecifier, frequency, format: Al.FormatMono16, buffersize: frequency);

            string deviceName = Alc.GetString(captureDevice, Alc.DeviceSpecifier);

            Console.WriteLine($"{deviceName} is open for capture.");

            if (args.Length > 0 && args[0] == "record")
            {
                while (true)
                {
                    Console.Write("Enter keyword name: ");
                    string keywordName = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(keywordName))                     // exit if nothing entered
                    {
                        break;
                    }

                    Alc.CaptureStart(captureDevice);
                    Console.WriteLine("recording keyword...");                     // need new line for intensity visualization

                    short[] samples = captureSamples(captureDevice, frequency, keywordLength);

                    Alc.CaptureStop(captureDevice);

                    int fileIndex = 0;
                    while (File.Exists($"{keywordName}.{fileIndex}.wav"))
                    {
                        fileIndex += 1;
                    }

                    // write sound file
                    {
                        string filename = $"{keywordName}.{fileIndex}.wav";
                        Debug.Assert(samples.Length >= keywordLength);
                        var wavFile = new WavFile(filename)
                        {
                            SamplesPerSecond = frequency, SamplesTotalCount = keywordLength                                                           /* trim samples */
                        };
                        wavFile.WriteMono16bit(samples);
                        Console.WriteLine($"wav file was saved.");
                    }

                    // create spectrogram and save as image
                    {
                        int width = (int)Math.Sqrt(samples.Length * 2);                         // TODO: make better formula for square images
                        var bins  = samples.Partition(size: width);

                        var spectrogram = new List <double[]>();

                        foreach (var bin in bins)
                        {
                            double[] histogram = calculateFFT(bin.ToArray());
                            spectrogram.Add(histogram);
                        }

                        using (Bitmap bitmap = new Bitmap(spectrogram.Count, spectrogram[0].Length))
                        {
                            for (int i = 0; i < spectrogram.Count; i++)
                            {
                                for (int j = 0; j < spectrogram[i].Length; j++)
                                {
                                    double value      = spectrogram[i][j];
                                    double pixelValue = Math.Max(0, Math.Min(255, value * 10));                                     // TODO: do not trim values, make better multiplying factor
                                    byte   color      = (byte)(pixelValue);
                                    bitmap.SetPixel(i, j, Color.FromArgb(color, color, color));
                                }
                            }
                            string filename = $"{keywordName}.{fileIndex}.png";
                            bitmap.Save(filename, ImageFormat.Png);
                            Console.WriteLine($"png file was saved.");
                        }
                    }
                }
            }
            else
            {
                Alc.CaptureStart(captureDevice);
                Console.WriteLine("listening for keyword...");                 // need new line for intensity visualization
                var reporter = new ClapDetector.Client.Reporter();
                while (true)
                {
                    short[] samples = captureSamples(captureDevice, frequency, keywordLength);
                    // TODO: generate spectrogram image and compare to existing models
                    Console.WriteLine("samples taken");

                    string replyMessage = await reporter.ReportClapAsync();

                    System.Console.WriteLine($"[{DateTime.UtcNow:HH:mm:ss.fff}]: {replyMessage}");
                }
                Alc.CaptureStop(captureDevice);
            }

            // clean up
            Alc.CaptureCloseDevice(captureDevice);
            Alc.MakeContextCurrent(IntPtr.Zero);
            //Alc.DestroyContext(context);
            //Alc.CloseDevice(audioDevice);
        }
Ejemplo n.º 29
0
        // Loads all available audio devices into the available_*_devices lists.
        static AudioDeviceEnumerator()
        {
            IntPtr        dummy_device  = IntPtr.Zero;
            ContextHandle dummy_context = ContextHandle.Zero;

            try
            {
                Debug.WriteLine("Enumerating audio devices.");
                Debug.Indent();

                // need a dummy context for correct results
                dummy_device  = Alc.OpenDevice(null);
                dummy_context = Alc.CreateContext(dummy_device, (int[])null);
                bool     dummy_success = Alc.MakeContextCurrent(dummy_context);
                AlcError dummy_error   = Alc.GetError(dummy_device);
                if (!dummy_success || dummy_error != AlcError.NoError)
                {
                    throw new AudioContextException("Failed to create dummy Context. Device (" + dummy_device.ToString() +
                                                    ") Context (" + dummy_context.Handle.ToString() +
                                                    ") MakeContextCurrent " + (dummy_success ? "succeeded" : "failed") +
                                                    ", Alc Error (" + dummy_error.ToString() + ") " + Alc.GetString(IntPtr.Zero, (AlcGetString)dummy_error));
                }

                // Get a list of all known playback devices, using best extension available
                if (Alc.IsExtensionPresent(IntPtr.Zero, "ALC_ENUMERATION_EXT"))
                {
                    version = AlcVersion.Alc1_1;
                    if (Alc.IsExtensionPresent(IntPtr.Zero, "ALC_ENUMERATE_ALL_EXT"))
                    {
                        available_playback_devices.AddRange(Alc.GetString(IntPtr.Zero, AlcGetStringList.AllDevicesSpecifier));
                        default_playback_device = Alc.GetString(IntPtr.Zero, AlcGetString.DefaultAllDevicesSpecifier);
                    }
                    else
                    {
                        available_playback_devices.AddRange(Alc.GetString(IntPtr.Zero, AlcGetStringList.DeviceSpecifier));
                        default_playback_device = Alc.GetString(IntPtr.Zero, AlcGetString.DefaultDeviceSpecifier);
                    }
                }
                else
                {
                    version = AlcVersion.Alc1_0;
                    Debug.Print("Device enumeration extension not available. Failed to enumerate playback devices.");
                }
                AlcError playback_err = Alc.GetError(dummy_device);
                if (playback_err != AlcError.NoError)
                {
                    throw new AudioContextException("Alc Error occured when querying available playback devices. " + playback_err.ToString());
                }

                // Get a list of all known recording devices, at least ALC_ENUMERATION_EXT is needed too
                if (version == AlcVersion.Alc1_1 && Alc.IsExtensionPresent(IntPtr.Zero, "ALC_EXT_CAPTURE"))
                {
                    available_recording_devices.AddRange(Alc.GetString(IntPtr.Zero, AlcGetStringList.CaptureDeviceSpecifier));
                    default_recording_device = Alc.GetString(IntPtr.Zero, AlcGetString.CaptureDefaultDeviceSpecifier);
                }
                else
                {
                    Debug.Print("Capture extension not available. Failed to enumerate recording devices.");
                }
                AlcError record_err = Alc.GetError(dummy_device);
                if (record_err != AlcError.NoError)
                {
                    throw new AudioContextException("Alc Error occured when querying available recording devices. " + record_err.ToString());
                }

#if DEBUG
                Debug.WriteLine("Found playback devices:");
                foreach (string s in available_playback_devices)
                {
                    Debug.WriteLine(s);
                }

                Debug.WriteLine("Default playback device: " + default_playback_device);

                Debug.WriteLine("Found recording devices:");
                foreach (string s in available_recording_devices)
                {
                    Debug.WriteLine(s);
                }

                Debug.WriteLine("Default recording device: " + default_recording_device);
#endif
            }
            catch (DllNotFoundException e)
            {
                Trace.WriteLine(e.ToString());
                openal_supported = false;
            }
            catch (AudioContextException ace)
            {
                Trace.WriteLine(ace.ToString());
                openal_supported = false;
            }
            finally
            {
                Debug.Unindent();

                if (openal_supported)
                {
                    try
                    {
                        // clean up the dummy context
                        Alc.MakeContextCurrent(ContextHandle.Zero);
                        if (dummy_context != ContextHandle.Zero && dummy_context.Handle != IntPtr.Zero)
                        {
                            Alc.DestroyContext(dummy_context);
                        }
                        if (dummy_device != IntPtr.Zero)
                        {
                            Alc.CloseDevice(dummy_device);
                        }
                    }
                    catch
                    {
                        openal_supported = false;
                    }
                }
            }
        }
Ejemplo n.º 30
0
        public SoundManager()
        {
            loadedSounds    = new List <Sound>();
            playingChannels = new SoundChannel[SOURCE_COUNT];

            streamingThread = null;

            categoryModifiers = null;

            alcDevice = Alc.OpenDevice(null);
            if (alcDevice == null)
            {
                throw new Exception("Failed to open an ALC device!");
            }

            AlcError alcError = Alc.GetError(alcDevice);

            if (alcError != AlcError.NoError)
            {
                //The audio device probably wasn't ready, this happens quite often
                //Just wait a while and try again
                Thread.Sleep(100);

                alcDevice = Alc.OpenDevice(null);

                alcError = Alc.GetError(alcDevice);
                if (alcError != AlcError.NoError)
                {
                    throw new Exception("Error initializing ALC device: " + alcError.ToString());
                }
            }

            int[] alcContextAttrs = new int[] { };
            alcContext = Alc.CreateContext(alcDevice, alcContextAttrs);
            if (alcContext == null)
            {
                throw new Exception("Failed to create an ALC context! (error code: " + Alc.GetError(alcDevice).ToString() + ")");
            }

            if (!Alc.MakeContextCurrent(alcContext))
            {
                throw new Exception("Failed to assign the current ALC context! (error code: " + Alc.GetError(alcDevice).ToString() + ")");
            }

            alcError = Alc.GetError(alcDevice);
            if (alcError != AlcError.NoError)
            {
                throw new Exception("Error after assigning ALC context: " + alcError.ToString());
            }

            ALError alError = ALError.NoError;

            alSources = new uint[SOURCE_COUNT];
            for (int i = 0; i < SOURCE_COUNT; i++)
            {
                AL.GenSource(out alSources[i]);
                alError = AL.GetError();
                if (alError != ALError.NoError)
                {
                    throw new Exception("Error generating alSource[" + i.ToString() + "]: " + AL.GetErrorString(alError));
                }

                if (!AL.IsSource(alSources[i]))
                {
                    throw new Exception("Generated alSource[" + i.ToString() + "] is invalid!");
                }

                AL.SourceStop(alSources[i]);
                alError = AL.GetError();
                if (alError != ALError.NoError)
                {
                    throw new Exception("Error stopping newly generated alSource[" + i.ToString() + "]: " + AL.GetErrorString(alError));
                }

                AL.Source(alSources[i], ALSourcef.MinGain, 0.0f);
                alError = AL.GetError();
                if (alError != ALError.NoError)
                {
                    throw new Exception("Error setting min gain: " + AL.GetErrorString(alError));
                }

                AL.Source(alSources[i], ALSourcef.MaxGain, 1.0f);
                alError = AL.GetError();
                if (alError != ALError.NoError)
                {
                    throw new Exception("Error setting max gain: " + AL.GetErrorString(alError));
                }

                AL.Source(alSources[i], ALSourcef.RolloffFactor, 1.0f);
                alError = AL.GetError();
                if (alError != ALError.NoError)
                {
                    throw new Exception("Error setting rolloff factor: " + AL.GetErrorString(alError));
                }
            }

            AL.DistanceModel(ALDistanceModel.LinearDistanceClamped);

            alError = AL.GetError();
            if (alError != ALError.NoError)
            {
                throw new Exception("Error setting distance model: " + AL.GetErrorString(alError));
            }

            if (Alc.IsExtensionPresent(IntPtr.Zero, "ALC_EXT_CAPTURE"))
            {
                alcCaptureDeviceNames = new List <string>(Alc.GetString(IntPtr.Zero, AlcGetStringList.CaptureDeviceSpecifier));
            }
            else
            {
                alcCaptureDeviceNames = null;
            }

            listenerOrientation  = new float[6];
            ListenerPosition     = Vector3.Zero;
            ListenerTargetVector = new Vector3(0.0f, 0.0f, 1.0f);
            ListenerUpVector     = new Vector3(0.0f, -1.0f, 0.0f);
        }