Provides methods to instantiate, use and destroy an audio context for playback. Static methods are provided to list available devices known by the driver.
Inheritance: IDisposable
Esempio n. 1
0
        public WaveSoundPlayer(WaveFile w, bool loop)
        {
            ac = new AudioContext ();

            bufferlist = new List<int> (NUM_BUFFERS);
            bufferlist.AddRange (AL.GenBuffers (NUM_BUFFERS));

            source = AL.GenSource ();
            this._PlayState = PlayState.NotLoaded;

            wfile = w;
            bufferlist.ForEach (x => {
                byte[] buf = new byte[BUFFER_SIZE];
                buf = wfile.DataBinary.ReadBytes(BUFFER_SIZE);
                AL.BufferData(x,wfile.SoundFormat,buf,buf.Length,wfile.SampleRate);
            });

            AL.SourceQueueBuffers (source, NUM_BUFFERS, bufferlist.ToArray ());
            if (loop)
                AL.Source (source, ALSourceb.Looping, true);

            System.Diagnostics.Debug.WriteLine (AL.GetSourceState(source).ToString());

            this._PlayState = PlayState.Stopped;
        }
Esempio n. 2
0
 public override void PlaySound(string assetName)
 {
     if (audioContext == null)
         audioContext = new AudioContext ();
     Thread soundThread = new Thread (() => this.PlaySoundThread (assetName, false));
     soundThread.Start ();
 }
Esempio n. 3
0
        /// <summary>
        /// MusicPlayer クラスの新しいインスタンスを初期化します。
        /// </summary>
        public MusicPlayer(MusicOptions options)
        {
            if (options == null)
                throw new ArgumentNullException("options");

            this.bufferSize = options.BufferSize;
            this.bufferCount = options.BufferCount;
            this.samplingRate = options.SamplingRate;
            this.updateInterval = options.UpdateInterval;

            this.context = new AudioContext();
            this.master = new Master(options.SamplingRate, 23);
            this.preset = new Preset();
            this.layer = new Dictionary<string, SequenceLayer>();

            this.source = AL.GenSource();
            this.buffers = AL.GenBuffers(this.bufferCount);
            this.sbuf = new short[this.bufferSize];
            this.fbuf = new float[this.bufferSize];

            foreach (int buffer in this.buffers)
                this.FillBuffer(buffer);

            AL.SourceQueueBuffers(this.source, this.buffers.Length, this.buffers);
            AL.SourcePlay(this.source);

            this.Updater = Task.Factory.StartNew(this.Update);
        }
Esempio n. 4
0
 public void Init(Client tclient, ClientCVar cvar)
 {
     if (Context != null)
     {
         Context.Dispose();
     }
     TheClient = tclient;
     CVars = cvar;
     Context = new AudioContext(AudioContext.DefaultDevice, 0, 0, false, true);
     Context.MakeCurrent();
     try
     {
         if (Microphone != null)
         {
             Microphone.StopEcho();
         }
         Microphone = new MicrophoneHandler(this);
     }
     catch (Exception ex)
     {
         SysConsole.Output("Loading microphone handling", ex);
     }
     if (Effects != null)
     {
         foreach (SoundEffect sfx in Effects.Values)
         {
             sfx.Internal = -2;
         }
     }
     Effects = new Dictionary<string, SoundEffect>();
     PlayingNow = new List<ActiveSound>();
     Noise = LoadSound(new DataStream(Convert.FromBase64String(NoiseDefault.NoiseB64)), "noise");
 }
Esempio n. 5
0
		public static void Init ()
		{
			if (context != null)
				return;
			
			context = new AudioContext ();
		}
Esempio n. 6
0
        internal OpenTKAudioCue(Stream data, AudioContext ac)
        {
            this.ac = ac;

            buffer = AL.GenBuffer();
            ac.CheckErrors();

            source = AL.GenSource();
            ac.CheckErrors();

            AL.Source(source, ALSourcef.Gain, (float)this.Volume);
            ac.CheckErrors();

            using (AudioReader ar = new AudioReader(data))
            {
                SoundData d = ar.ReadToEnd();
                AL.BufferData(source, d);
                ac.CheckErrors();
            }

            AL.Source(source, ALSourcei.Buffer, buffer);
            ac.CheckErrors();

            this.VolumeChanged += new VolumeChangedEventHandler(OpenTKAudioCue_VolumeChanged);
            this.BalanceChanged += new BalanceChangedEventHandler(OpenTKAudioCue_BalanceChanged);
            this.FadeChanged += new FadeChangedEventHandler(OpenTKAudioCue_FadeChanged);
        }
Esempio n. 7
0
        public Player()
        {
            _context = new AudioContext();

            for (int i = 0; i < 10; ++i)
                _freeSources.Enqueue(AL.GenSource());
        }
Esempio n. 8
0
        //int NextPlayingBuffer;
        //int numPLayedBuffer;
        /// <summary>
        /// Constructor for Sound class
        /// </summary>
        /// <param name="StartThread">Are we starting the sound thread?</param>
        public Sound(bool StartThread)
        {
            disposed = false;
            SoundList = new Dictionary<string, SoundType>();
            context = new AudioContext(); // default audio device
            lock (context)
            {
                context.MakeCurrent();
            }
            //XRamExtension XRam = new XRamExtension();

            /*SoundBuffers = AL.GenBuffers(4); // number of buffers
            SoundSource = AL.GenSource();
            SoundStreamSource = AL.GenSource();*/
            RunSoundThread = true;

            isPlaying = false;
            NowPlayingName = string.Empty;
            //NowPlayingBuffer = -1;
            NextPlayingName = string.Empty;
            //NextPlayingBuffer = -1;
            //numPLayedBuffer = 0; //??
            /*OpenTK.Vector3 v3 = new OpenTK.Vector3(1, 1, 1);
            AL.Source(AL.GenBuffer(), ALSource3f.Position, ref v3);*/

            //Debug.WriteLine(AL.Get(ALGetString.Version));

            tr = new System.Threading.Thread(new ThreadStart(PlayThread));
            if (StartThread)
            {
                RunThread();
            }
        }
Esempio n. 9
0
        public static void Main()
        {
            using (AudioContext context = new AudioContext())
            {
                int buffer = AL.GenBuffer();
                int source = AL.GenSource();
                int state;

                int channels, bits_per_sample, sample_rate;
                byte[] sound_data = LoadWave(File.Open(filename, FileMode.Open), out channels, out bits_per_sample, out sample_rate);
                AL.BufferData(buffer, GetSoundFormat(channels, bits_per_sample), sound_data, sound_data.Length, sample_rate);

                AL.Source(source, ALSourcei.Buffer, buffer);
                AL.SourcePlay(source);

                Trace.Write("Playing");

                // Query the source to find out when it stops playing.
                do
                {
                    Thread.Sleep(250);
                    Trace.Write(".");
                    AL.GetSource(source, ALGetSourcei.SourceState, out state);
                }
                while ((ALSourceState)state == ALSourceState.Playing);

                Trace.WriteLine("");

                AL.SourceStop(source);
                AL.DeleteSource(source);
                AL.DeleteBuffer(buffer);
            }
        }
Esempio n. 10
0
 static Sound()
 {
     App.Init();
     audio = new AudioContext();
     AL.DistanceModel(ALDistanceModel.ExponentDistanceClamped);
     Listener = Vec2.Zero;
 }
Esempio n. 11
0
 public AudioOutputAL()
 {
     try {
         context = new AudioContext();
     } catch( Exception e ) {
         Console.WriteLine( e );
     }
 }
Esempio n. 12
0
 public void Initialize(OpenTK.GameWindow window) {
     if (isInitialized) {
         Error("Trying to double initialize sound manager!");
     }
     context = new AudioContext();
     managedSounds = new List<SoundInstance>();
     isInitialized = true;
 }
Esempio n. 13
0
 public void MakeCurrent()
 {
     if (this.disposed)
     {
         throw new ObjectDisposedException(this.GetType().FullName);
     }
     AudioContext.MakeCurrent(this);
 }
Esempio n. 14
0
		public void Dispose()
		{
			if (_disposed) return;

			_context.Dispose();
			_context = null;

			_disposed = true;
		}
Esempio n. 15
0
 private static void MakeCurrent(AudioContext context)
 {
     lock (AudioContext.audio_context_lock)
     {
         if (!Alc.MakeContextCurrent(context != null ? context.context_handle : ContextHandle.Zero))
         {
             throw new AudioContextException(string.Format("ALC {0} error detected at {1}.", (object)((object)Alc.GetError(context != null ? (IntPtr)context.context_handle : IntPtr.Zero)).ToString(), context != null ? (object)context.ToString() : (object)"null"));
         }
     }
 }
Esempio n. 16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="WavePlayer"/> class.
        /// </summary>
        private WavePlayer()
        {
            this.context = new AudioContext();

            this.buffer = AL.GenBuffer();
            this.source = AL.GenSource();

            this.thread = new Thread(new ThreadStart(this.SourceStateListen));
            this.thread.Start();
        }
Esempio n. 17
0
        public static void Main()
        {
            using (AudioContext context = new AudioContext())
            {
                Trace.WriteLine("Testing WaveReader({0}).ReadToEnd()", filename);

                EffectsExtension efx = new EffectsExtension();

                int buffer = AL.GenBuffer();
                int source = AL.GenSource();
                int state;

                int effect = efx.GenEffect();
                int slot = efx.GenAuxiliaryEffectSlot();

                efx.BindEffect(effect, EfxEffectType.Reverb);
                efx.Effect(effect, EfxEffectf.ReverbDecayTime, 3.0f);
                efx.Effect(effect, EfxEffectf.ReverbDecayHFRatio, 0.91f);
                efx.Effect(effect, EfxEffectf.ReverbDensity, 0.7f);
                efx.Effect(effect, EfxEffectf.ReverbDiffusion, 0.9f);
                efx.Effect(effect, EfxEffectf.ReverbRoomRolloffFactor, 3.1f);
                efx.Effect(effect, EfxEffectf.ReverbReflectionsGain, 0.723f);
                efx.Effect(effect, EfxEffectf.ReverbReflectionsDelay, 0.03f);
                efx.Effect(effect, EfxEffectf.ReverbGain, 0.23f);

                efx.AuxiliaryEffectSlot(slot, EfxAuxiliaryi.EffectslotEffect, effect);

                int channels, bits, rate;
                byte[] data = Playback.LoadWave(File.Open(filename, FileMode.Open), out channels, out bits, out rate);
                AL.BufferData(buffer, Playback.GetSoundFormat(channels, bits), data, data.Length, rate);

                AL.Source(source, ALSourcef.ConeOuterGain, 1.0f);
                AL.Source(source, ALSourcei.Buffer, buffer);
                AL.SourcePlay(source);

                Trace.Write("Playing");

                // Query the source to find out when it stops playing.
                do
                {
                    Thread.Sleep(250);
                    Trace.Write(".");
                    AL.GetSource(source, ALGetSourcei.SourceState, out state);
                }
                while ((ALSourceState)state == ALSourceState.Playing);

                Trace.WriteLine("");

                AL.SourceStop(source);
                AL.DeleteSource(source);
                AL.DeleteBuffer(buffer);
                efx.DeleteEffect(effect);
                efx.DeleteAuxiliaryEffectSlot(slot);
            }
        }
Esempio n. 18
0
File: Game.cs Progetto: mokujin/DN
        public Game(Size screenSize, bool fullscreen)
            : base(screenSize.Width, screenSize.Height, GraphicsMode.Default, "Devil's nightmare", fullscreen ? GameWindowFlags.Fullscreen : GameWindowFlags.Default)
        {
            g_screenSize = screenSize;
            g_screenRect = new Rectangle(0, 0, screenSize.Width, screenSize.Height);

            GraphicsDevice.Instance.Initialize(g_screenSize.Width, g_screenSize.Height);
            VSync = VSyncMode.On;
            audioContext = new AudioContext();
            new AudioManager(16, 8, 4096, true);
        }
Esempio n. 19
0
        public EngineWindow()
            : base(1200, 800, new GraphicsMode(32, 24, 8, 4), "OpenTK", GameWindowFlags.Default, DisplayDevice.Default, 3, 1, GraphicsContextFlags.ForwardCompatible)
        {
            Global.window = this;
            string versionOpenGL = GL.GetString(StringName.Version);
            string shaderVersion = GL.GetString(StringName.ShadingLanguageVersion);
            Console.WriteLine("OpenGL: " + versionOpenGL);
            Console.WriteLine("GLSL: " + shaderVersion);

            AC = new AudioContext();
        }
Esempio n. 20
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);
        }
Esempio n. 21
0
        public MainWindow()
            : base("MD", 640, 480)
        {
            this.WindowState = WindowState.Maximized;

            // Client area
            VariableContainer clientarea = new VariableContainer();

            // Menu items
            MenuItem[] menuitems = new MenuItem[]
            {
                MenuItem.Create("File", new MenuItem[]
                {
                    MenuItem.Create("Import", delegate
                    {
                        using(var fd = new WinForms.OpenFileDialog())
                        {
                            fd.Filter = "MP3 Files |*.mp3";
                            if (fd.ShowDialog() == WinForms.DialogResult.OK)
                            {
                                string file = fd.FileName;
                                AudioContext ac = new AudioContext();
                                MemoryAudioSource mas = new MP3AudioFeed(file).Copy(4096, 4096 * 100);

                                SpectrogramView sp = new SpectrogramView(mas);
                                clientarea.Client = sp;

                                AudioOutput ao = new AudioOutput(mas.Play);
                                ao.Play();
                            }
                            else
                            {
                                return;
                            }
                        }
                    }),
                    MenuItem.Create("Exit", delegate
                    {
                        this.Close();
                    })
                })
            };

            // Menu and splitter
            Menu menu = new Menu(menuitems);
            SplitContainer sc = new SplitContainer(Axis.Vertical, menu.WithBorder(0.0, 0.0, 0.0, 1.0), clientarea);
            sc.NearSize = 30.0;

            // Main layer container
            LayerContainer lc = new LayerContainer(sc);

            this.Control = lc;
        }
Esempio n. 22
0
        /// <summary>Load and buffer all the sounds for the game.</summary>
        internal static void LoadSounds()
        {
            if (!Config.SoundEnabled) return;

            try
            {
                _audioContext = new AudioContext();
                //Debug.WriteLine("Audio device: " + _audioContext.CurrentDevice);
            }
            catch (Exception ex)
            {
                //if we cant create an audio context then disable sounds in the config and return
                Debug.WriteLine("Error creating Audio Context: " + ex.Message);
                Config.SoundEnabled = false;
                Config.Save();
                return;
            }

            int soundsCount = Enum.GetValues(typeof(SoundType)).Length;
            _buffer = new int[soundsCount];
            _source = new int[soundsCount];
            try
            {
                for (int i = 0; i < soundsCount; i++)
                {
                    _source[i] = AL.GenSource();
                    _buffer[i] = AL.GenBuffer();
                }

                BufferSound(Resources.SoundFiles.AddBlock, SoundType.AddBlock);
                BufferSound(Resources.SoundFiles.ItemPickup, SoundType.ItemPickup);
                BufferSound(Resources.SoundFiles.JumpOutOfWater, SoundType.JumpOutOfWater);
                BufferSound(Resources.SoundFiles.Message, SoundType.Message);
                BufferSound(Resources.SoundFiles.PlayerConnect, SoundType.PlayerConnect);
                BufferSound(Resources.SoundFiles.PlayerLanding, SoundType.PlayerLanding);
                BufferSound(Resources.SoundFiles.Splash, SoundType.Splash);
                BufferSound(Resources.SoundFiles.RemoveBlock, SoundType.RemoveBlock);
                BufferSound(Resources.SoundFiles.WaterBubbles, SoundType.WaterBubbles);
                BufferSound(Resources.SoundFiles.TimeToDreamMono, SoundType.MusicTimeToDreamMono);

                //start music here so it only gets started if sound is enabled and there were no exceptions loading sounds
                if (Config.MusicEnabled) Music.StartMusic();
            }
            catch (Exception ex)
            {
                throw new Exception("Error buffering sounds. If the problem persists try running with sound disabled.\n" + ex.Message);
            }

            //wire sound events
            PerformanceHost.OnSecondElapsed += PerformanceHost_OnSecondElapsed;
            PerformanceHost.OnFiveSecondsElapsed += PerformanceHost_OnFiveSecondsElapsed;
        }
Esempio n. 23
0
		void IDualityBackend.Init()
		{
			AudioLibraryLoader.LoadAudioLibrary();

			// Initialize OpenTK, if not done yet
			DefaultOpenTKBackendPlugin.InitOpenTK();
			
			Log.Core.Write("Available devices:" + Environment.NewLine + "{0}", 
				AudioContext.AvailableDevices.ToString(d => d == AudioContext.DefaultDevice ? d + " (Default)" : d, "," + Environment.NewLine));

			// Create OpenAL audio context
			this.context = new AudioContext();
			Log.Core.Write("Current device: {0}", this.context.CurrentDevice);

			// Create extension interfaces
			try
			{
				this.extFx = new EffectsExtension();
				if (!this.extFx.IsInitialized)
					this.extFx = null;
			}
			catch (Exception)
			{
				this.extFx = null;
			}

			activeInstance = this;

			// Log all OpenAL specs for diagnostic purposes
			LogOpenALSpecs();

			// Generate OpenAL source pool
			for (int i = 0; i < 256; i++)
			{
				int newSrc = AL.GenSource();
				if (!Backend.DefaultOpenTK.AudioBackend.CheckOpenALErrors(true))
					this.sourcePool.Push(newSrc);
				else
					break;
			}
			this.availSources = this.sourcePool.Count;
			Log.Core.Write("{0} sources available", this.sourcePool.Count);
			
			// Set up the streaming thread
			this.streamWorkerEnd = false;
			this.streamWorkerQueue = new List<NativeAudioSource>();
			this.streamWorkerQueueEvent = new AutoResetEvent(false);
			this.streamWorker = new Thread(ThreadStreamFunc);
			this.streamWorker.IsBackground = true;
			this.streamWorker.Start();
		}
Esempio n. 24
0
 /// <summary>
 /// Constructor
 /// </summary>
 public OggPlayerVBN()
 {
     m_PlayerState = OggPlayerStatus.Waiting;
     m_BufferSize = 8096;				// Using 8KB buffer segments
     m_MaxTotalBufferSize = 8388608;		// Max of 8MB buffered at any time
     m_TickInterval = 1;
     m_TickEnabled = false;
     m_PrebufferDelay = 250;				// 1/4 of a second to pre-buffer before playback/seeking
     m_UpdateDelay = 5;
     m_PauseBuffer = true;
     m_Context = new AudioContext();
     if (!InitSource()) { throw new OggPlayerSourceException("Source initialisation failed"); }
     ResetPlayerCondition();
 }
Esempio n. 25
0
        public void Dispose()
        {
            if (_oggStreamer != null)
            {
                _oggStreamer.Dispose();
                _oggStreamer = null;
            }

            if (_context != null)
            {
                _context.Dispose();
                _context = null;
            }
        }
        /// <summary>
        /// Initializes OpenAL and loads two sound clips.
        /// </summary>
        public InteractivePlayerForm()
        {
            // Setup OpenTK audio stuff
            AudioContext ac = new AudioContext();
            XRamExtension xram = new XRamExtension();

            // Load the .ogg files
            guitar = new AudioClip("GuitarSample.ogg");
            boing = new AudioClip("BoingSample.ogg");

            externalClip = null;

            InitializeComponent();
        }
Esempio n. 27
0
        public AudioDevice( IWindow window )
        {
            try
            {
                audioContext = new AudioContext ();
            }
            catch ( Exception e )
            {
                throw new PlatformNotSupportedException ( string.Format (
                    "Audio device is not available or OpenAL library is not exist: {0}",
                    e ) );
            }

            audioList = new List<IAudio> ();
        }
Esempio n. 28
0
        public bool Init()
        {
            if (_Initialized)
                CloseAll();

            AC = new AudioContext();
            AC.MakeCurrent();
            

            closeproc = new CLOSEPROC(close_proc);
            _Initialized = true;

            _Streams = new List<AudioStreams>();
            return true;
        }
Esempio n. 29
0
        /// <summary>
        /// Constructor
        /// </summary>
        public OggPlayerFBN()
        {
            m_PlayerState = OggPlayerStatus.Waiting;

            m_UpdateDelay = 10;
            m_Context = new AudioContext();			// Initialise the AudioContext
            m_BufferCount = 32;
            m_BufferSize = 4096;
            m_Buffers = new uint[m_BufferCount];				// We're using four buffers so we always have a supply of data

            m_TickInterval = 1;			// Default tick is every second
            m_TickEnabled = false;		// Tick event is disabled by default

            if (!InitSource()) { throw new OggPlayerSourceException("Source initialisation failed"); }
        }
Esempio n. 30
0
        public override bool Initialize()
        {
            try
            {
                _audioContext = new AudioContext();
                Initialized = true;
            }
            catch (Exception e)
            {
                Logger.Error("Could not initialize Audio Context", e);
                return false;
            }

            return true;
        }
Esempio n. 31
0
        public AudioDevice(string deviceName)
        {
            if (deviceName != null && !AvailableDevices.Contains(deviceName))
            {
                throw new InvalidOperationException(string.Format("AudioDevice \"{0}\" does not exist.", deviceName));
            }

            Context = new OpenTK.Audio.AudioContext(deviceName, 0, 15, true, true, AudioContext.MaxAuxiliarySends.UseDriverDefault);
            CheckAlcError();
            deviceHandle = Alc.GetContextsDevice(Alc.GetCurrentContext());
            CheckAlcError();
            Efx = new EffectsExtension();
            CheckAlcError();

            int[] val = new int[4];
            DeviceName    = Context.CurrentDevice;
            VendorName    = AL.Get(ALGetString.Vendor);
            Renderer      = AL.Get(ALGetString.Renderer);
            DriverVersion = AL.Get(ALGetString.Version);
            int major, minor;

            Alc.GetInteger(deviceHandle, AlcGetInteger.MajorVersion, 1, val);
            major = val[0];
            Alc.GetInteger(deviceHandle, AlcGetInteger.MinorVersion, 1, val);
            minor   = val[0];
            Version = new Version(major, minor);
            Alc.GetInteger(deviceHandle, AlcGetInteger.EfxMajorVersion, 1, val);
            major = val[0];
            Alc.GetInteger(deviceHandle, AlcGetInteger.EfxMinorVersion, 1, val);
            minor      = val[0];
            EfxVersion = new Version(major, minor);
            Alc.GetInteger(deviceHandle, AlcGetInteger.EfxMaxAuxiliarySends, 1, val);
            MaxRoutes  = val[0];
            Extensions = new List <string>(AL.Get(ALGetString.Extensions).Split(' ')).AsReadOnly();

            AL.DistanceModel(ALDistanceModel.ExponentDistance);

            CheckAudioCapabilities(LogLevel.Verbose);
            LogDiagnostics(LogLevel.Verbose);

            Factory  = new AudioFactory(this);
            Listener = new AudioListener(this);
            Listener.Orientation(Vector3.UnitY, Vector3.UnitZ);

            updateTaskCancelation = new CancellationTokenSource();
            updateTask            = Task.Factory.StartNew(Update);
        }
Esempio n. 32
0
 public ALAudioBackend()
 {
     try
     {
         _context = new AudioContext();
     }
     catch (AudioContextException e1)
     {
         Debug.WriteLine("Failed to create audio context, audio will not be played.");
         Debug.WriteLine(e1.ToString());
     }
     catch (DllNotFoundException e2)
     {
         Debug.WriteLine("Failed to find OpenAL Soft dll, audio will not be played.");
         Debug.WriteLine(e2.ToString());
     }
 }
Esempio n. 33
0
        public AudioSystem(Common.IO.FileSystem fileSystem)
        {
            if (fileSystem == null)
                throw new ArgumentNullException("fileSystem");

            Context = new AudioContext();
            Util.CheckOpenAlErrors();

            AL.DistanceModel(ALDistanceModel.InverseDistanceClamped);
            Util.CheckOpenAlErrors();

            DecoderFactory = new DecoderFactory();
            DecoderFactory.Register(".ogg", data => new Decoders.OggDecoder(data));

            AudioBufferManager = new AudioBufferManager(DecoderFactory, fileSystem);
            Sources = new List<AudioSource>();
        }