protected virtual void Dispose(bool disposing) { if (!_isDisposed) { // Delete the buffer AL.DeleteBuffer(_bufferId); AL.DeleteSource(_sourceId); if (_context != ALContext.Null) { ALC.MakeContextCurrent(ALContext.Null); ALC.DestroyContext(_context); } _context = ALContext.Null; if (_device != IntPtr.Zero) { ALC.CloseDevice(_device); } _device = ALDevice.Null; _isDisposed = true; } }
private OpenALHost(ALDevice device, ALContext context, Vector3 forward, Vector3 up) { this.device = device; this.context = context; this.forward = forward; this.up = up; }
/// <summary> /// Loads the API for the given extension, using the base API. /// </summary> /// <param name="device">The device of the context.</param> /// <param name="baseAPI">The base API instance.</param> /// <typeparam name="TContextExtension">The extension type.</typeparam> /// <returns>The extension.</returns> /// <exception cref="ExtensionNotSupportedException">Thrown if the API doesn't support the extension.</exception> internal static TContextExtension LoadContextExtension <TContextExtension>(ALContext baseApi) where TContextExtension : NativeExtension <ALContext> { return(baseApi.IsExtensionPresent(ExtensionAttribute.GetExtensionAttribute(typeof(TContextExtension)).Name) ? (TContextExtension)Activator.CreateInstance(typeof(TContextExtension), baseApi.Context) : null); }
private unsafe PinMameController(IInputContext input) { _pinMame = PinMame.PinMame.Instance(); _pinMame.OnGameStarted += OnGameStarted; _pinMame.OnDisplayAvailable += OnDisplayAvailable; _pinMame.OnDisplayUpdated += OnDisplayUpdated; _pinMame.OnAudioAvailable += OnAudioAvailable; _pinMame.OnAudioUpdated += OnAudioUpdated; _pinMame.OnConsoleDataUpdated += OnConsoleDataUpdated; _pinMame.OnGameEnded += OnGameEnded; _pinMame.IsKeyPressed += IsKeyPressed; _pinMame.SetHandleKeyboard(true); _dmdController = DmdController.Instance(); _input = input; foreach (var keyboard in _input.Keyboards) { keyboard.KeyDown += (arg1, arg2, arg3) => { if (_keycodeMap.TryGetValue(arg2, out var keycode)) { Logger.Trace($"KeyDown() {keycode} ({(int)keycode})"); _keypress[(int)keycode] = 1; } }; keyboard.KeyUp += (arg1, arg2, arg3) => { if (_keycodeMap.TryGetValue(arg2, out var keycode)) { Logger.Trace($"KeyUp() {keycode} ({(int)keycode})"); _keypress[(int)keycode] = 0; } }; } _al = AL.GetApi(true); ALContext alContext = ALContext.GetApi(true); var device = alContext.OpenDevice(""); if (device != null) { alContext.MakeContextCurrent( alContext.CreateContext(device, null)); _audioSource = _al.GenSource(); _audioBuffers = _al.GenBuffers(_maxAudioBuffers); } else { Logger.Error("PinMameController(): Could not create device"); } }
private AudioContext() { var deviceName = findDeviceName(); device = ALC.OpenDevice(deviceName); ctx = ALC.CreateContext(device, (int[])null !); ALC.MakeContextCurrent(ctx); }
public void Destroy() { ALC.MakeContextCurrent(ALContext.Null); ALC.DestroyContext(_context); _context = ALContext.Null; ALC.CloseDevice(_device); _device = ALDevice.Null; }
public OpenAlAudioBackend() { _al = AL.GetApi(true); // So. // Current version of Silk.NET is smashed and doesn't let us use soft_oal // for the ALContext (but does for the OpenAL API itself). // // This'll be fixed in two weeks. // // Oh and they protected the native constructor. Ew. That'll also // be fixed in two weeks. // // For now... YOUR IDE WILL SCREAM AT YOU IN TERROR BECAUSE I'M USING // SUPER SPOOKY SCARY EVIL REFLECTION STUFF but... _alc = (ALContext)typeof(ALContext) .GetConstructor( BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.Instance, null, new[] { typeof(INativeContext) }, null )?.Invoke(new[] { _al.Context }); unsafe { var device = _alc.OpenDevice(string.Empty); var error = _alc.GetError(device); if (error != ContextError.NoError) { throw new InvalidOperationException("OpenAL threw an error: " + error); } var ctx = _alc.CreateContext(device, null); error = _alc.GetError(device); if (error != ContextError.NoError) { throw new InvalidOperationException("OpenAL threw an error: " + error); } _alc.MakeContextCurrent(ctx); error = _alc.GetError(device); if (error != ContextError.NoError) { throw new InvalidOperationException("OpenAL threw an error: " + error); } } ThrowOnError(); }
public void Create() { if (_device == ALDevice.Null) { _device = ALC.OpenDevice(null); } if (_context == ALContext.Null) { _context = ALC.CreateContext(_device, (int[])null); } ALC.MakeContextCurrent(_context); }
public void Init() { _device = ALC.OpenDevice(null); _attributes = new ALContextAttributes(); _context = ALC.CreateContext(_device, _attributes); ALC.MakeContextCurrent(_context); _bufferId = AL.GenBuffers(1)[0]; _sourceId = AL.GenSources(1)[0]; //If data is byte, use ALFormat.Stereo16. For float use ALFormat.StereoFloat32Ext switch (Path.GetExtension(_fileName)) { case ".ogg": _oggSoundData = DecodeSound.LoadNVorbisData(_fileName); AL.BufferData(_bufferId, MapFormat(_oggSoundData.Format), _oggSoundData.BufferData, _oggSoundData.BufferData.Length * sizeof(float), _oggSoundData.SampleRate); break; case ".mp3": _mp3AndWaveSoundData = DecodeSound.LoadMP3SharpData(_fileName); AL.BufferData(_bufferId, MapFormat(_mp3AndWaveSoundData.Format), _mp3AndWaveSoundData.BufferData, _mp3AndWaveSoundData.BufferData.Length, _mp3AndWaveSoundData.SampleRate); break; case ".wav": _mp3AndWaveSoundData = DecodeSound.LoadWaveFile(_fileName); //Helpers.SaveData(_mp3AndWaveSoundData.BufferData, 4, @"C:\Temp\tone-data.csv"); // Sends the buffer data to the sound card AL.BufferData(_bufferId, MapFormat(_mp3AndWaveSoundData.Format), _mp3AndWaveSoundData.BufferData, _mp3AndWaveSoundData.BufferData.Length, _mp3AndWaveSoundData.SampleRate); break; } // Bind the buffer to the source AL.Source(_sourceId, ALSourcei.Buffer, _bufferId); }
void Initialize() { device = ALC.OpenDevice(null); unsafe { context = ALC.CreateContext(device, (int *)null); ALC.MakeContextCurrent(context); } //Console.WriteLine(Alc.GetString(IntPtr.Zero, AlcGetString.AllDevicesSpecifier)); version = AL.Get(ALGetString.Version); vendor = AL.Get(ALGetString.Vendor); renderer = AL.Get(ALGetString.Extensions); }
internal static void Init() { // Jos initialisointia on jo kutsuttu. if (initialized) { return; } initialized = true; // Don't initialize OpenAL in headless mode. if (CommandLineOptions.Headless ?? Game.Instance?.Headless ?? false) { return; } ALContext alc = null; try { // Yritetään ladata OpenAL Soft. // Jos softia ei ole saatavilla (Esim. M1 tms. ARM suorittimella varustettu kone), // Koitetaan sitten käyttää laitteen omaa OpenAL kirjastoa. // TODO: Kumpi on oikeasti parempi? Pitäisikö logiikan mennä toisinpäin? alc = ALContext.GetApi(true); al = AL.GetApi(true); } catch { alc = ALContext.GetApi(); al = AL.GetApi(); } var device = alc.OpenDevice(""); if (device == null) { al = null; throw new AudioDeviceException("Unable to initialize OpenAL device."); } var context = alc.CreateContext(device, null); alc.MakeContextCurrent(context); al.DistanceModel(DistanceModel.InverseDistance); al.GetError(); al.SetListenerProperty(ListenerVector3.Position, 0, 0, 1); }
public OpenALHardwareDeviceDriver() { _device = ALC.OpenDevice(""); _context = ALC.CreateContext(_device, new ALContextAttributes()); _updateRequiredEvent = new ManualResetEvent(false); _sessions = new List <OpenALHardwareDeviceSession>(); _stillRunning = true; _updaterThread = new Thread(Update) { Name = "HardwareDeviceDriver.OpenAL" }; _updaterThread.Start(); }
public void Dispose() { if (context != ALContext.Null) { ALC.MakeContextCurrent(ALContext.Null); ALC.DestroyContext(context); } context = ALContext.Null; if (device != IntPtr.Zero) { ALC.CloseDevice(device); } device = ALDevice.Null; }
public AudioOutput(int channels = 1, int sampleRate = 44100) { if (channels < 1 || channels > 2) { throw new ArgumentOutOfRangeException(nameof(channels)); } if (sampleRate < 2000 || sampleRate > 200000) { throw new ArgumentOutOfRangeException(nameof(sampleRate)); } try { al = AL.GetApi(true); alContext = ALContext.GetApi(true); } catch { al = AL.GetApi(false); alContext = ALContext.GetApi(false); } device = alContext.OpenDevice(""); Available = device != null; if (Available) { context = alContext.CreateContext(device, null); alContext.MakeContextCurrent(context); if (al.GetError() != AudioError.NoError) { Available = false; if (context != null) { alContext.DestroyContext(context); } alContext.CloseDevice(device); al.Dispose(); alContext.Dispose(); disposed = true; return; } source = al.GenSource(); al.SetSourceProperty(source, SourceBoolean.Looping, true); al.SetSourceProperty(source, SourceFloat.Gain, 1.0f); } }
public unsafe void GetEnumerationContextStringList() { using var alc = ALContext.GetApi(true); var dev = alc.OpenDevice(string.Empty); if (dev != null && alc.TryGetExtension(dev, out Enumeration ext)) { ext.GetStringList(dev, Extensions.Enumeration.GetEnumerationContextStringList.DeviceSpecifiers); } else { throw new($"dev {(nint) dev}, ext not loaded"); } Assert.True(alc.CloseDevice(dev)); }
public OpenALBackend() { if (ALInstance != null) { throw new InvalidOperationException("Only one ALInstance can exist at a time."); } ALInstance = this; var audioDevice = ALC.OpenDevice(null); _context = ALC.CreateContext(audioDevice, new int[] { }); ALC.MakeContextCurrent(_context); _sourcePool = new ALSourcePool(); }
static OpenALContext() { //string deviceName = ALC.GetString(ALDevice.Null, AlcGetString.DefaultDeviceSpecifier); //foreach (var name in ALC.GetStringList(GetEnumerationStringList.DeviceSpecifier)) //{ // if (name.Contains("OpenAL Soft")) // { // deviceName = name; // } //} device = ALC.OpenDevice(null); context = ALC.CreateContext(device, (int[])null); ALC.MakeContextCurrent(context); }
/// <summary> /// Initialize the <see cref="SoundSystem"/>. /// </summary> /// <param name="bufferSize"></param> public void Initialize(int bufferSize = DEFAULT_BUFFER_SIZE) { if (_context == null) { _context = new ALContext(); } BufferSize = bufferSize; XRam = new XRamExtension(); Efx = new EffectsExtension(); // Init empty sources _sources = AL.GenSources(MAXIMUM_NUMBER_OF_SOURCES); ALChecker.CheckError(); }
public Window(GameWindowSettings settings, NativeWindowSettings nativeSettings) : base(settings, nativeSettings) { device = ALC.OpenDevice(""); context = ALC.CreateContext(device, new ALContextAttributes() { Frequency = 44100 }); ALC.MakeContextCurrent(context); Console.WriteLine("Version : " + AL.Get(ALGetString.Version)); Console.WriteLine("Vendor : " + AL.Get(ALGetString.Vendor)); Console.WriteLine("Renderer: " + AL.Get(ALGetString.Renderer)); _gameboy = new Gameboy(() => { return(new AudioEmitter()); }); string path = "Roms/Games/Mario Deluxe.gbc "; string[] args = Environment.GetCommandLineArgs(); if (args.Length > 1) { path = args[1]; } if (!File.Exists(path)) { Console.WriteLine(path); Console.WriteLine("Invalid usage... GBSharp [rom]"); foreach (string s in args) { Console.WriteLine("S: " + s); } throw new Exception(); } Cartridge cartridge = Cartridge.Load(path); //Cartridge cartridge = GetNextTestRom(); //CartridgeLoader.LoadDataIntoMemory(_mmu, GetNextTestRom(), 0x00); _gameboy.LoadCartridge(cartridge); thread = new Thread(new ThreadStart(_gameboy.Run)); _isAlive = true; thread.Start(); }
public static void ExampleSound() { unsafe { //Initialize ALDevice device = ALC.ALC.OpenDevice(null); ALContext context = ALC.ALC.CreateContext(device, (int *)null); ALC.ALC.MakeContextCurrent(context); string version = AL.AL.Get(ALGetString.Version); string vendor = AL.AL.Get(ALGetString.Vendor); string renderer = AL.AL.Get(ALGetString.Renderer); Console.WriteLine(version); Console.WriteLine(vendor); Console.WriteLine(renderer); Console.ReadKey(); //Process int buffers, source; AL.AL.GenBuffer(out buffers); AL.AL.GenSource(out source); int sampleFreq = 44100; double dt = 2 * Math.PI / sampleFreq; double amp = 0.5; int freq = 440; int dataCount = sampleFreq / freq; short[] sinData = new short[dataCount]; for (int i = 0; i < sinData.Length; ++i) { sinData[i] = (short)(amp * short.MaxValue * Math.Sin(i * dt * freq)); } AL.AL.BufferData(buffers, ALFormat.Mono16, sinData, sinData.Length * sizeof(short), sampleFreq); AL.AL.Source(source, ALSourcei.Buffer, buffers); AL.AL.Source(source, ALSourceb.Looping, true); AL.AL.SourcePlay(source); Console.ReadKey(); ///Dispose ALC.ALC.CloseDevice(device); } }
public AudioPlayer() { audioDevice = ALC.OpenDevice(null); if (audioDevice == null) { Console.WriteLine("Unable to create audio device"); return; } audioContext = ALC.CreateContext(audioDevice, (int[])null); ALC.MakeContextCurrent(audioContext); audioSource = AL.GenSource(); AL.Listener(ALListener3f.Position, 0, 0, 0); AL.Listener(ALListener3f.Velocity, 0, 0, 0); var orientation = new Vector3(0, 0, 0); AL.Listener(ALListenerfv.Orientation, ref orientation, ref orientation); fastForward = false; audioDisabled = false; }
protected override void OnStop() { // Cleanup: nuke our context if we have it. This is hacky and bad - we should really destroy // our buffers and sources. I have _no_ idea if OpenAL will leak memory. if (_context != null) { XPlane.Trace.WriteLine($"[OpenAL Sample] Deleting my context 0x{(ulong)_context.Handle:X8}"); ALC.DestroyContext(_context); _context = default; } if (_device != null) { ALC.CloseDevice(_device); _device = default; } _flightLoop.Dispose(); _flightLoop = null; Menu.PluginsMenu.Dispose(); }
public unsafe void TestALContextTryGetExtension(bool isPresent) { // never do anything demonstrated in this test using var loader = new LamdaNativeContext(GetLoader(isPresent, out var loaderPtr, out var ctxLoaderPtr)); using var alc = new ALContext(loader); void Test <T>() where T : NativeExtension <ALContext> { _testOutputHelper.WriteLine(typeof(T).ToString()); Assert.Equal(alc.TryGetExtension(null, out T ext), isPresent); Assert.Equal(ext is not null, isPresent); } Test <Capture>(); Test <Enumeration>(); Test <EnumerateAll>(); Test <CaptureEnumerationEnumeration>(); Test <EffectExtensionContext>(); SilkMarshal.Free(loaderPtr); SilkMarshal.Free(ctxLoaderPtr); }
internal SoundPlayer() { _alDevice = ALC.OpenDevice(null); var contextAttributes = new ALContextAttributes(); _alContext = ALC.CreateContext(_alDevice, contextAttributes); ALC.MakeContextCurrent(_alContext); _bufferedAudioSources = new BufferedAudioSource[4]; for (int i = 0; i < ChannelCount; i++) { _bufferedAudioSources[i] = new BufferedAudioSource(); } //noise and wave channel are panned left initially _bufferedAudioSources[2].SetPosition(SoundOutputTerminal.Left); _bufferedAudioSources[3].SetPosition(SoundOutputTerminal.Left); //TODO: Start/restart the sources synchronously }
public static bool InitDevice() { ALDevice audioDev = ALC.OpenDevice(null); AlcError err = ALC.GetError(audioDev); if (err != AlcError.NoError) { return(false); } ALContext aLContext = ALC.CreateContext(audioDev, new int[0]); bool makeRs = ALC.MakeContextCurrent(aLContext); err = ALC.GetError(audioDev); if (!makeRs || err != AlcError.NoError) { return(false); } //ALCdevice* inputDevice = alcCaptureOpenDevice(NULL, FREQ, AL_FORMAT_MONO16, FREQ / 2); ALCaptureDevice captureDev = ALC.CaptureOpenDevice(null, FREQ, ALFormat.Mono16, FREQ / 2); // FREQ ALC.CaptureStart(captureDev); err = ALC.GetError(audioDev); if (err != AlcError.NoError) { return(false); } int[] buffer = AL.GenBuffers(16); err = ALC.GetError(audioDev); if (err != AlcError.NoError) { return(false); } return(true); }
public AudioDevice() { device = ALC.OpenDevice(string.Empty); if (device.Equals(ALDevice.Null)) { return; } context = ALC.CreateContext(device, new ALContextAttributes()); ALC.MakeContextCurrent(context); var error = AL.GetError(); if (error != ALError.NoError) { throw new FailingSoundDeviceException($"Failed to open audio device. Error code: {error}."); } MusicSource = new MusicAudioSource(); IntenseMusicSource = new MusicAudioSource(); MiscSources = new GameAudioSource[miscSourceCount]; for (int i = 0; i < miscSourceCount; i++) { MiscSources[i] = new GameAudioSource(); } GameSources = new GameAudioSource[gameSourceCount]; for (int i = 0; i < gameSourceCount; i++) { GameSources[i] = new GameAudioSource(); } initialized = true; }
protected override bool OnStart() { try { _al = AL.GetApi(); _alc = ALContext.GetApi(); } catch (Exception ex) { XPlane.Trace.WriteLine($"[OpenAL Sample] Failed to initialize Open AL: " + ex); return(false); } _flightLoop = FlightLoop.Create(FlightLoopPhaseType.BeforeFlightModel, InitSound); _flightLoop.Schedule(-1, false); Menu.PluginsMenu .AddItem("OpenAL Sample (Private Context)", item => item.CreateSubMenu() .AddItem("Play Sound", out _, PlaySound) ); return(true); }
private unsafe float InitSound(float elapsedSinceLastCall, float elapsedTimeSinceLastFlightLoop, int counter) { CheckError(); var oldContext = ALC.GetCurrentContext(); if (oldContext == default) { XPlane.Trace.WriteLine("[OpenAL Sample] I found no OpenAL, I will be the first to init."); _device = ALC.OpenDevice(null); if (_device == null) { XPlane.Trace.WriteLine("[OpenAL Sample] Could not open the default OpenAL device."); return(0); } _context = ALC.CreateContext(_device, new ALContextAttributes()); if (_context == null) { ALC.CloseDevice(_device); _device = default; XPlane.Trace.WriteLine("[OpenAL Sample] Could not open the default OpenAL device."); return(0); } ALC.MakeContextCurrent(_context); XPlane.Trace.WriteLine("[OpenAL Sample] Created the Open AL context."); var hardware = ALC.GetString(_device, AlcGetString.DeviceSpecifier); var extensions = ALC.GetString(_device, AlcGetString.Extensions); var major = ALC.GetInteger(_device, AlcGetInteger.MajorVersion); var minor = ALC.GetInteger(_device, AlcGetInteger.MinorVersion); XPlane.Trace.WriteLine($"[OpenAL Sample] OpenAL version : {major}.{minor}"); XPlane.Trace.WriteLine($"[OpenAL Sample] OpenAL hardware : {hardware}"); XPlane.Trace.WriteLine($"[OpenAL Sample] OpenAL extensions: {extensions}"); CheckError(); } else { XPlane.Trace.WriteLine($"[OpenAL Sample] I found someone else's context: {(ulong)oldContext.Handle:X8}"); } var path = Path.Combine(Path.GetDirectoryName(PluginInfo.ThisPlugin.FilePath), "sound.wav"); // Generate 1 source and load a buffer of audio. _soundSource = AL.GenSource(); CheckError(); _soundBuffer = WavHelper.LoadWav(path); XPlane.Trace.WriteLine($"[OpenAL Sample] Loaded {_soundBuffer} from {path}."); // Basic initialization code to play a sound: specify the buffer the source is playing, as well as some // sound parameters. This doesn't play the sound - it's just one-time initialization. AL.Source(_soundSource, ALSourcei.Buffer, _soundBuffer); AL.Source(_soundSource, ALSourcef.Pitch, 1f); AL.Source(_soundSource, ALSourcef.Gain, 1f); AL.Source(_soundSource, ALSourceb.Looping, false); AL.Source(_soundSource, ALSource3f.Position, 0f, 0f, 0f); AL.Source(_soundSource, ALSource3f.Velocity, 0f, 0f, 0f); CheckError(); return(0); }
private float InitSound(float elapsedSinceLastCall, float elapsedTimeSinceLastFlightLoop, int counter) { CheckError(); // We have to save the old context and restore it later, so that we don't interfere with X-Plane // and other plugins. var oldContext = ALC.GetCurrentContext(); // Try to create our own default device and context. If we fail, we're dead, we won't play any sound. _device = ALC.OpenDevice(null); if (_device == null) { XPlane.Trace.WriteLine("[OpenAL Sample] Could not open the default OpenAL device."); return(0); } _context = ALC.CreateContext(_device, new ALContextAttributes()); if (_context == null) { if (oldContext != default) { ALC.MakeContextCurrent(oldContext); } ALC.CloseDevice(_device); _device = default; XPlane.Trace.WriteLine("[OpenAL Sample] Could not create a context."); return(0); } // Make our context current, so that OpenAL commands affect our, um, stuff. ALC.MakeContextCurrent(_context); var path = Path.Combine(Path.GetDirectoryName(PluginInfo.ThisPlugin.FilePath), "sound.wav"); // Generate 1 source and load a buffer of audio. AL.GenSource(out _soundSource); CheckError(); _soundBuffer = WavHelper.LoadWav(path); XPlane.Trace.WriteLine($"[OpenAL Sample] Loaded {_soundBuffer} from {path}."); // Basic initialization code to play a sound: specify the buffer the source is playing, as well as some // sound parameters. This doesn't play the sound - it's just one-time initialization. AL.Source(_soundSource, ALSourcei.Buffer, _soundBuffer); AL.Source(_soundSource, ALSourcef.Pitch, 1f); AL.Source(_soundSource, ALSourcef.Gain, 1f); AL.Source(_soundSource, ALSourceb.Looping, false); AL.Source(_soundSource, ALSource3f.Position, 0f, 0f, 0f); AL.Source(_soundSource, ALSource3f.Velocity, 0f, 0f, 0f); CheckError(); // Finally: put back the old context _if_ we had one. If old_ctx was null, X-Plane isn't using OpenAL. if (oldContext != default) { ALC.MakeContextCurrent(oldContext); } return(0); }
public static extern ALDevice GetContextsDevice(ALContext context);