Esempio n. 1
0
        public static void Init()
        {
            string deviceName = ALC.GetString(ALDevice.Null, AlcGetString.DefaultDeviceSpecifier);
            var    device     = ALC.OpenDevice(deviceName);
            var    context    = ALC.CreateContext(device, (int[])null);

            ALC.MakeContextCurrent(context);
        }
Esempio n. 2
0
    private static string findDeviceName()
    {
        // Start with the default device.
        var deviceName = ALC.GetString(ALDevice.Null, AlcGetString.DefaultDeviceSpecifier);

        // Find all remaining devices. Prefer OpenAL Soft if it exists.
        var devices = ALC.GetStringList(GetEnumerationStringList.DeviceSpecifier);

        foreach (var d in devices)
        {
            if (d.Contains("OpenAL Soft"))
            {
                deviceName = d;
            }
        }

        return(deviceName);
    }
Esempio n. 3
0
        public bool Init()
        {
            try
            {
                var deviceName = ALC.GetString(ALDevice.Null, AlcGetString.DefaultDeviceSpecifier);
                OpenTkSound.device = ALC.OpenDevice(deviceName);
                var context = ALC.CreateContext(OpenTkSound.device, (int[])null);
                ALC.MakeContextCurrent(context);
                this.checkError();
                this.initOpenALExtensions();
            }
            catch (Exception e)
            {
                Com.Printf(e.Message + '\n');

                return(false);
            }

            // set the master volume
            this.s_volume = Cvar.Get("s_volume", "0.7", Defines.CVAR_ARCHIVE);

            AL.GenBuffers(this.buffers.Length, this.buffers);
            var count = Channel.init(this.buffers, OpenTkSound.efxSlot);

            Com.Printf("... using " + count + " channels\n");
            AL.DistanceModel(ALDistanceModel.InverseDistanceClamped);

            Cmd.AddCommand("play", () => { this.Play(); });

            Cmd.AddCommand("stopsound", () => { this.StopAllSounds(); });

            Cmd.AddCommand("soundlist", () => { this.SoundList(); });

            Cmd.AddCommand("soundinfo", () => { this.SoundInfo_f(); });

            OpenTkSound.num_sfx = 0;

            Com.Println("sound sampling rate: 44100Hz");

            this.StopAllSounds();
            Com.Println("------------------------------------");

            return(true);
        }
Esempio n. 4
0
        public static OpenALHost Open(Vector3 forward, Vector3 up)
        {
            var devices = ALC.GetStringList(GetEnumerationStringList.DeviceSpecifier);

            // Get the default device, then go though all devices and select the AL soft device if it exists.
            string deviceName = ALC.GetString(ALDevice.Null, AlcGetString.DefaultDeviceSpecifier);

            foreach (var d in devices)
            {
                if (d.Contains("OpenAL Soft"))
                {
                    deviceName = d;
                }
            }

            var device  = ALC.OpenDevice(deviceName);
            var context = ALC.CreateContext(device, new int[] {
                AlSoft.HRTF, AlSoft.Enable
            });

            ALC.MakeContextCurrent(context);

            return(new OpenALHost(device, context, forward, up));
        }
        internal static void PopulateCaptureDevices()
        {
            // clear microphones
            _allMicrophones.Clear();

            Default = null;

            // default device
            string defaultDevice = ALC.GetString(IntPtr.Zero, ALCGetString.CaptureDefaultDeviceSpecifier);

#if WINDOWS || DESKTOPGL
            // enumarating capture devices
            IntPtr deviceList = ALC.alcGetString(IntPtr.Zero, (int)ALCGetString.CaptureDeviceSpecifier);

            // we need to marshal a string array
            string?deviceIdentifier = Marshal.PtrToStringAnsi(deviceList);
            while (!string.IsNullOrEmpty(deviceIdentifier))
            {
                var 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 a 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
        }
Esempio n. 6
0
        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);
        }
Esempio n. 7
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting OpenAL!");
            var devices = ALC.GetStringList(GetEnumerationStringList.DeviceSpecifier);

            // Get the default device, then go though all devices and select the AL soft device if it exists.
            string deviceName = ALC.GetString(ALDevice.Null, AlcGetString.DefaultDeviceSpecifier);

            foreach (var d in devices)
            {
                if (d.Contains("OpenAL Soft"))
                {
                    deviceName = d;
                }
            }

            var device  = ALC.OpenDevice(deviceName);
            var context = ALC.CreateContext(device, (int[])null);

            ALC.MakeContextCurrent(context);

            CheckALError("Start");

            // Playback the recorded data
            CheckALError("Before data");
            AL.GenBuffer(out int alBuffer);
            AL.GenBuffer(out int backBuffer);
            AL.Listener(ALListenerf.Gain, 0.1f);

            AL.GenSource(out int alSource);
            AL.Source(alSource, ALSourcef.Gain, 1f);

            // var get samples from map
            var map     = @"D:\H2vMaps\01a_tutorial.map";
            var factory = new MapFactory(Path.GetDirectoryName(map));
            var h2map   = factory.Load(Path.GetFileName(map));

            if (h2map is not H2vMap scene)
            {
                throw new NotSupportedException("Only Vista maps are supported in this tool");
            }

            var soundMapping = scene.GetTag(scene.Globals.SoundInfos[0].SoundMap);

            var soundTags = scene.GetLocalTagsOfType <SoundTag>();

            var maxSoundId = soundTags.Max(s => s.SoundEntryIndex);

            // TODO: multiplayer sounds are referencing the wrong ugh! tag

            var i = 0;

            foreach (var snd in soundTags)
            {
                var enc = snd.Encoding switch
                {
                    EncodingType.ImaAdpcmMono => AudioEncoding.MonoImaAdpcm,
                    EncodingType.ImaAdpcmStereo => AudioEncoding.StereoImaAdpcm,
                    _ => AudioEncoding.Mono16,
                };

                var sr = snd.SampleRate switch
                {
                    Core.Tags.SampleRate.hz22k05 => Audio.SampleRate._22k05,
                    Core.Tags.SampleRate.hz44k1 => Audio.SampleRate._44k1,
                    _ => Audio.SampleRate._44k1
                };

                if (enc != AudioEncoding.Mono16)
                {
                    continue;
                }

                var name = snd.Name.Substring(snd.Name.LastIndexOf("\\", snd.Name.LastIndexOf("\\") - 1) + 1).Replace('\\', '_');

                Console.WriteLine($"[{i++}] {snd.Option1}-{snd.Option2}-{snd.Option3}-{snd.SampleRate}-{snd.Encoding}-{snd.Format2}-{snd.Unknown}-{snd.UsuallyMaxValue}-{snd.UsuallyZero} {name}");

                var filenameFormat = $"{name}.{snd.SampleRate}-{snd.Encoding}-{snd.Format2}-{snd.Unknown}-{snd.UsuallyZero}-{snd.UsuallyMaxValue}.{{0}}.sound";

                var soundEntry = soundMapping.SoundEntries[snd.SoundEntryIndex];

                for (var s = 0; s < soundEntry.NamedSoundClipCount; s++)
                {
                    var clipIndex = soundEntry.NamedSoundClipIndex + s;

                    var clipInfo = soundMapping.NamedSoundClips[clipIndex];

                    var clipFilename = string.Format(filenameFormat, s);

                    var clipSize = 0;
                    for (var c = 0; c < clipInfo.SoundDataChunkCount; c++)
                    {
                        var chunk = soundMapping.SoundDataChunks[clipInfo.SoundDataChunkIndex + c];
                        clipSize += (int)(chunk.Length & 0x3FFFFFFF);
                    }

                    Span <byte> clipData        = new byte[clipSize];
                    var         clipDataCurrent = 0;

                    for (var c = 0; c < clipInfo.SoundDataChunkCount; c++)
                    {
                        var chunk = soundMapping.SoundDataChunks[clipInfo.SoundDataChunkIndex + c];

                        var len       = (int)(chunk.Length & 0x3FFFFFFF);
                        var chunkData = scene.ReadData(chunk.Offset.Location, chunk.Offset, len);

                        chunkData.Span.CopyTo(clipData.Slice(clipDataCurrent));
                        clipDataCurrent += len;
                    }

                    Interlocked.Exchange(ref backBuffer, Interlocked.Exchange(ref alBuffer, backBuffer));
                    AL.SourceStop(alSource);
                    BufferData(enc, sr, clipData.Slice(96), alBuffer);
                    CheckALError("After buffer");
                    AL.Source(alSource, ALSourcei.Buffer, alBuffer);
                    AL.SourcePlay(alSource);

                    while (AL.GetSourceState(alSource) == ALSourceState.Playing)
                    {
                        Thread.Sleep(100);
                    }

                    // Only play first variant
                    break;
                }
            }

            ALC.MakeContextCurrent(ALContext.Null);
            ALC.DestroyContext(context);
            ALC.CloseDevice(device);

            Console.WriteLine("done");
            Console.ReadLine();
        }