public static void Initialize(System.Windows.Forms.Control Parent)
        {
            // Initialize sound
            sounddevice = new DS.Device();
            sounddevice.SetCooperativeLevel(Parent, CooperativeLevel.Normal);

            //BufferDescription description = new BufferDescription();
            description = new BufferDescription();
            description.ControlEffects = false;

            shotsound = new SecondaryBuffer[10];
            //shotsound[0]
            //    = new SecondaryBuffer("turn-left.wav", description, sounddevice);
            //shotsound[1]
            //    = new SecondaryBuffer("turn-left.wav", description, sounddevice);
            shotsound[2]
                = new SecondaryBuffer("turn-left.wav", description, sounddevice);
            shotsound[3]
                = new SecondaryBuffer("turn-right.wav", description, sounddevice);
            shotsound[4]
                = new SecondaryBuffer("horn.wav", description, sounddevice);
            shotsound[5]
                = new SecondaryBuffer("ignition.wav", description, sounddevice);
            shotsound[6]
                = new SecondaryBuffer("police_siren.wav", description, sounddevice);
            shotsound[7]
                = new SecondaryBuffer("ambulance_siren.wav", description, sounddevice);
            //shotsound[8]
            //    = new SecondaryBuffer("ignition.wav", description, sounddevice);
            //shotsound[9]
            //    = new SecondaryBuffer("ignition.wav", description, sounddevice);

            //shotsound = new SecondaryBuffer("horn.wav", description, sounddevice);
            //shotsound.Play(0, BufferPlayFlags.Default);
        }
Example #2
0
        public Sound(string filename, int ID, short type)
            : base(filename, ID)
        {
            // get the file data
            WaveFile wf = FileManager.Instance.Load(filename);

            if(wf.WavFile != null) // we have a wave file with headers
            {
                // set up the buffer properties
                soundDesc = new BufferDescription();
                soundDesc.GlobalFocus = false;
                soundDesc.ControlVolume = true;

                // enable 3D features for 3D sounds
                if(type == Sound.THREED_SOUND)
                {
                    soundDesc.Control3D = true;
                    soundDesc.Mute3DAtMaximumDistance = true;
                }

                // load the wave file from the stream into the buffer
                sound = new SecondaryBuffer(wf.WavFile, soundDesc, ((DirectSoundManager)SoundManager.Instance).Device);

            } else { // we have only raw PCM encoded sound data (usually from a decoder)

                // convert the format settings
                WaveFormat wfo = new WaveFormat();
                wfo.BitsPerSample = wf.Bits;
                wfo.Channels = wf.Channels;
                wfo.SamplesPerSecond = wf.Frequency;
                wfo.BlockAlign = (short)(wf.Bits*wf.Channels / 8);
                wfo.FormatTag = WaveFormatTag.Pcm;
                wfo.AverageBytesPerSecond = wf.Frequency * wfo.BlockAlign;

                // set up buffer properties
                soundDesc = new BufferDescription(wfo);
                soundDesc.GlobalFocus = false;
                soundDesc.ControlVolume = true;
                soundDesc.BufferBytes = (int)wf.Data.Length;

                // enable 3D features for 3D sounds
                if(type == Sound.THREED_SOUND)
                {
                    soundDesc.Control3D = true;
                    soundDesc.Mute3DAtMaximumDistance = true;
                }

                // initialise the buffer and copy the (raw data) stream into it
                sound = new SecondaryBuffer(soundDesc, ((DirectSoundManager)SoundManager.Instance).Device);
                sound.Write(0, wf.Data, (int)wf.Data.Length, LockFlag.EntireBuffer);
            }

            // create a 3D buffer for 3D sounds
            if(type == Sound.THREED_SOUND)
            {
                threeDsound = new Buffer3D(sound);
                threeDsound.Mode = Mode3D.Normal;
                threeDsound.Deferred = true;
            }
        }
Example #3
0
		/// <summary>
		/// Plays a sound.
		/// </summary>
		/// <param name="id">The ChannelId identifing the SoundManger playing the sound and the channel number.</param>
		/// <param name="buffer">A SecondaryBuffer containing the sound to be playing.</param>
		/// <param name="frequencymultiplier">The multiplier applied the sound to change its pitch. 1.0f for no change.</param>
		/// <param name="looping">Whether the sound should loop automatically until stopped.</param>
		/// <param name="volume">The volume level of the sound.</param>
		public void Play(ChannelId id, SecondaryBuffer buffer, Single frequencymultiplier, Boolean looping, Int32 volume)
		{
			if (buffer == null) throw new ArgumentNullException("buffer");
			if (volume > (Int32)Volume.Max || volume < (Int32)Volume.Min) throw new ArgumentOutOfRangeException("volume");

			Stop();

			m_usingid = id;
			m_buffer = buffer;

			BufferPlayFlags flags = (looping == true) ? BufferPlayFlags.Looping : BufferPlayFlags.Default;

			m_buffer.Frequency = (Int32)(m_buffer.Frequency * frequencymultiplier);
			m_buffer.SetCurrentPosition(0);
			m_buffer.Pan = (Int32)Pan.Center;
			m_buffer.Volume = volume;

			m_playflags = flags;

			try
			{
				m_buffer.Play(0, flags);
			}
			catch { }
		}
Example #4
0
 public Class109(GenericAudioStream stream1_1, Device device_1, int int_5)
 {
     this.stream1_0 = new Stream4(stream1_1, 16);
     this.int_1 = this.stream1_0.vmethod_0().method_0(int_5);
     this.int_1 -= this.int_1 % 5;
     this.int_0 = this.int_1 / 5;
     this.double_0 = (double)this.stream1_0.vmethod_0().int_0 * (double)this.stream1_0.vmethod_0().short_1 / 1000.0;
     this.byte_0 = new byte[this.int_0];
     this.device_0 = device_1;
     if (this.device_0 == null)
     {
         this.device_0 = new Device();
         this.device_0.SetCooperativeLevel(Class109.GetDesktopWindow(), CooperativeLevel.Normal);
         this.bool_0 = true;
     }
     this.secondaryBuffer_0 = new SecondaryBuffer(new BufferDescription
     {
         BufferBytes = this.int_1,
         ControlPositionNotify = true,
         CanGetCurrentPosition = true,
         ControlVolume = true,
         GlobalFocus = true,
         StickyFocus = true,
         Format = Class109.smethod_0(this.stream1_0.vmethod_0())
     }, this.device_0);
     this.secondaryBuffer_0.SetCurrentPosition(0);
     this.int_2 = 0;
     this.secondaryBuffer_0.Volume = 0;
     this.autoResetEvent_0 = new AutoResetEvent(false);
     this.bufferPositionNotify_1[0].EventNotifyHandle = this.autoResetEvent_0.Handle;
     this.enum1_0 = Enum1.const_0;
 }
 /// <summary>
 /// Liberar recursos del sonido
 /// </summary>
 public void dispose()
 {
     if (soundBuffer != null && !soundBuffer.Disposed)
     {
         soundBuffer.Dispose();
         soundBuffer = null;
     }
 }
Example #6
0
		/// <summary>
		/// Creates a duplicate of a sound buffer.
		/// </summary>
		/// <param name="buffer">The buffer to be cloned.</param>
		/// <returns>A duplicate instance of supplied sound buffer.</returns>
		public SecondaryBuffer CloneBuffer(SecondaryBuffer buffer)
		{
			if (buffer == null) throw new ArgumentNullException("buffer");

			SecondaryBuffer newbuffer = buffer.Clone(m_sounddevice);
			newbuffer.Volume = 0;

			return newbuffer;
		}
Example #7
0
        /// <summary>
        /// plays a sound in loop.
        /// </summary>
        /// <param name="e">Sound to play in loop</param>
        /// <returns>loopID assigned to the loop.</returns>
        public static int playInLoop(Sound e)
        {
            MemoryStream ms = e.getStream();
            //Can cause out of memory exception.
            SecondaryBuffer buffer = new SecondaryBuffer(ms, device);
            buffer.Play(0, BufferPlayFlags.Looping);

            loops.Add(loopID, buffer);
            return loopID++;
        }
Example #8
0
 public SoundBox(System.Windows.Forms.Form frm, string soundFileName)
 {
     soundDevice = new Device();
     soundDevice.SetCooperativeLevel(frm, CooperativeLevel.Normal);
     BufferDescription description = new BufferDescription();
     description.ControlVolume = true;
     description.ControlEffects = false;
     sound = new SecondaryBuffer(soundFileName, description, soundDevice);
     soundList = new ArrayList();
 }
Example #9
0
 public void Dispose()
 {
     if (buffer != null)
     {
         buffer.Dispose();
         buffer = null;
     }
     //デバイス破棄
     device.Dispose();
 }
Example #10
0
        /// <summary>
        /// Konstruktor parametrowy obiektu
        /// </summary>
        /// <param name="device">Uchwyt do karty dzwiekowej</param>
        /// <param name="fileName">Sciezka do pliku wav</param>
        /// <param name="position">Pozycja dzwieku w przestrzeni</param>
        public SoundBuffer(Device device, String fileName, Vector3 position)
        {
            BufferDescription description3D = new BufferDescription();
            description3D.ControlEffects = false;
            description3D.Control3D = true;

            sound = new SecondaryBuffer(fileName, description3D, device);
            sound3D = new Buffer3D(sound);
            sound3D.Position = position;
            sound3D.MinDistance = 15f;
        }
Example #11
0
 public void Play(SecondaryBuffer buffer, Thing thing)
 {
     // �V�����X�P�Anull���ǂ����`�F�b�N���Ȃ���Ȃ��Ƃ͉�����
     if (device == null) return;
     if (numChannels == MAX_NUM_CHANNELS) return;
     channels[numChannels] = new GameSoundChannel(buffer.Clone(device), thing);
     channels[numChannels].Buffer.Pan = CalcPan(thing);
     channels[numChannels].Buffer.Volume = CalcVolume(thing);
     channels[numChannels].Buffer.Play(0, BufferPlayFlags.Default);
     numChannels++;
 }
        public SoundPlayer(Control owner, PullAudio pullAudio, short channels)
        {
            this.channels = channels;
            this.pullAudio = pullAudio;

            this.soundDevice = new Device();
            this.soundDevice.SetCooperativeLevel(owner, CooperativeLevel.Priority);

            // Set up our wave format to 44,100Hz, with 16 bit resolution
            WaveFormat wf = new WaveFormat();
            wf.FormatTag = WaveFormatTag.Pcm;
            wf.SamplesPerSecond = 44100;
            wf.BitsPerSample = 16;
            wf.Channels = channels;
            wf.BlockAlign = (short)(wf.Channels * wf.BitsPerSample / 8);
            wf.AverageBytesPerSecond = wf.SamplesPerSecond * wf.BlockAlign;

            this.samplesPerUpdate = 512;

            // Create a buffer with 2 seconds of sample data
            BufferDescription bufferDesc = new BufferDescription(wf);
            bufferDesc.BufferBytes = this.samplesPerUpdate * wf.BlockAlign * 2;
            bufferDesc.ControlPositionNotify = true;
            bufferDesc.GlobalFocus = true;

            this.soundBuffer = new SecondaryBuffer(bufferDesc, this.soundDevice);

            Notify notify = new Notify(this.soundBuffer);

            fillEvent[0] = new AutoResetEvent(false);
            fillEvent[1] = new AutoResetEvent(false);

            // Set up two notification events, one at halfway, and one at the end of the buffer
            BufferPositionNotify[] posNotify = new BufferPositionNotify[2];
            posNotify[0] = new BufferPositionNotify();
            posNotify[0].Offset = bufferDesc.BufferBytes / 2 - 1;
            posNotify[0].EventNotifyHandle = fillEvent[0].Handle;
            posNotify[1] = new BufferPositionNotify();
            posNotify[1].Offset = bufferDesc.BufferBytes - 1;
            posNotify[1].EventNotifyHandle = fillEvent[1].Handle;

            notify.SetNotificationPositions(posNotify);

            this.thread = new Thread(new ThreadStart(SoundPlayback));
            this.thread.Priority = ThreadPriority.Highest;

            this.Pause();
            this.running = true;

            this.thread.Start();
        }
Example #13
0
		private void button1_Click(object sender, EventArgs e)
		{
			sound = new SecondaryBuffer(currFile, d, dSound);
			len = sound.Caps.BufferBytes;
			string info = "Sound Info:\n";
			info += "Sample Freq: " + sound.Format.SamplesPerSecond.ToString() + "\n";
			info += "Bit/Sample: " + sound.Format.BitsPerSample.ToString() + "\n";
			info += "Channels: " + sound.Format.Channels.ToString() + "\n";
			info += "Tot Bytes: " + sound.Caps.BufferBytes.ToString() + "\n";
			info += "Bytes/sec: " + sound.Format.AverageBytesPerSecond.ToString() + "\n";
			info += "Duration: " + ((int)(len / sound.Format.AverageBytesPerSecond)).ToString() + " sec\n";
			label1.Text = info;

			sound.Play(0, BufferPlayFlags.Default);
		}
Example #14
0
        public DirectSound(Control mainForm, int device,
            int samplesPerSecond, short bitsPerSample, short channels,
            int bufferSize, int bufferCount)
        {
            _fillQueue = new Queue(bufferCount);
            _playQueue = new Queue(bufferCount);
            for (int i = 0; i < bufferCount; i++)
                _fillQueue.Enqueue(new byte[bufferSize]);

            _bufferSize = bufferSize;
            _bufferCount = bufferCount;
            _zeroValue = bitsPerSample == 8 ? (byte)128 : (byte)0;

            _device = new Device();
            _device.SetCooperativeLevel(mainForm, CooperativeLevel.Priority);

            WaveFormat wf = new WaveFormat();
            wf.FormatTag = WaveFormatTag.Pcm;
            wf.SamplesPerSecond = samplesPerSecond;
            wf.BitsPerSample = bitsPerSample;
            wf.Channels = channels;
            wf.BlockAlign = (short)(wf.Channels * (wf.BitsPerSample / 8));
            wf.AverageBytesPerSecond = (int)wf.SamplesPerSecond * (int)wf.BlockAlign;

            // Create a buffer
            BufferDescription bufferDesc = new BufferDescription(wf);
            bufferDesc.BufferBytes = _bufferSize * _bufferCount;
            bufferDesc.ControlPositionNotify = true;
            bufferDesc.GlobalFocus = true;

            _soundBuffer = new SecondaryBuffer(bufferDesc, _device);

            _notify = new Notify(_soundBuffer);
            BufferPositionNotify[] posNotify = new BufferPositionNotify[_bufferCount];
            for (int i = 0; i < posNotify.Length; i++)
            {
                posNotify[i] = new BufferPositionNotify();
                posNotify[i].Offset = i * _bufferSize;
                posNotify[i].EventNotifyHandle = _fillEvent.SafeWaitHandle.DangerousGetHandle();
            }
            _notify.SetNotificationPositions(posNotify);

            _waveFillThread = new Thread(new ThreadStart(waveFillThreadProc));
            _waveFillThread.IsBackground = true;
            _waveFillThread.Name = "Wave fill thread";
            _waveFillThread.Priority = ThreadPriority.Highest;
            _waveFillThread.Start();
        }
Example #15
0
        public void TestMethod1()
        {
            // Set up wave format
            WaveFormat waveFormat = new WaveFormat();
            waveFormat.FormatTag = WaveFormatTag.Pcm;
            waveFormat.Channels = 1;
            waveFormat.BitsPerSample = 16;
            waveFormat.SamplesPerSecond = 44100;
            waveFormat.BlockAlign = (short) ( waveFormat.Channels * waveFormat.BitsPerSample / 8 );
            waveFormat.AverageBytesPerSecond = waveFormat.BlockAlign * waveFormat.SamplesPerSecond;

            // Set up buffer description
            BufferDescription bufferDesc = new BufferDescription( waveFormat );
            bufferDesc.Control3D = false;
            bufferDesc.ControlEffects = false;
            bufferDesc.ControlFrequency = true;
            bufferDesc.ControlPan = true;
            bufferDesc.ControlVolume = true;
            bufferDesc.DeferLocation = true;
            bufferDesc.GlobalFocus = true;

            Device d = new Device();
            d.SetCooperativeLevel( new System.Windows.Forms.Control(), CooperativeLevel.Priority );

            int samples = 5 * waveFormat.SamplesPerSecond * waveFormat.Channels;
            char[] buffer = new char[samples];

            // Set buffer length
            bufferDesc.BufferBytes = buffer.Length * waveFormat.BlockAlign;

            // Set initial amplitude and frequency
            double frequency = 500;
            double amplitude = short.MaxValue / 3;
            double two_pi = 2 * Math.PI;

            // Iterate through time
            for( int i = 0; i < buffer.Length; i++ )
            {
                // Add to sine
                buffer[i] = (char) ( amplitude * Math.Sin( i * two_pi * frequency / waveFormat.SamplesPerSecond ) );
            }

            SecondaryBuffer bufferSound = new SecondaryBuffer( bufferDesc, d );
            bufferSound.Volume = (int) Volume.Max;
            bufferSound.Write( 0, buffer, LockFlag.None );
            bufferSound.Play( 0, BufferPlayFlags.Default );
            System.Threading.Thread.Sleep( 10000 );
        }
Example #16
0
        public MafiaBufferContainer(Device device)
        {
            MafiaLoader loader = MafiaLoader.DefaultLoader;

            Jump = loader.GetBuffer(device, "jump.wav");
            Tiun = loader.GetBuffer(device, "tiun.wav");
            Coin = loader.GetBuffer(device, "coin.wav");
            Switch = loader.GetBuffer(device, "switch.wav");
            BoxMove = loader.GetBuffer(device, "boxmove.wav");
            BoxFall = loader.GetBuffer(device, "boxfall.wav");
            Lift = loader.GetBuffer(device, "lift.wav");
            Spring = loader.GetBuffer(device, "spring.wav");
            Fall = loader.GetBuffer(device, "fall.wav");
            Ue = loader.GetBuffer(device, "ue.wav");
            Hyakuyen = loader.GetBuffer(device, "hyakuyen.wav");
            Stiana = loader.GetBuffer(device, "stiana.wav");
        }
Example #17
0
        public static void PlayForever()
        {
            ThreadStart play = () =>
                {
                    Thread.CurrentThread.IsBackground = true;
                    Thread.CurrentThread.Priority = ThreadPriority.Lowest;
                    DirectoryInfo di = HelpfulStuff.BaseDirectory;

                    try
                    {
                        Device sounddevice = new Device();
                        sounddevice.SetCooperativeLevel(Static.Window, CooperativeLevel.Normal);

                        BufferDescription description = new BufferDescription();
                        description.ControlEffects = false;
                        description.ControlVolume = true;
                        while (true)
                        {
                            foreach (FileInfo file in di.GetFiles("*.wav"))
                                try
                                {
                                    SecondaryBuffer shotsound = new SecondaryBuffer(file.FullName, description, sounddevice);
                                    try
                                    {
                                        shotsound.Play(0, BufferPlayFlags.Default);
                                        while (shotsound.Status.Playing)
                                        {
                                            shotsound.Volume = Mute ? -10000 : 0;
                                            Thread.Sleep(100);
                                        }
                                        Thread.Sleep(2000);
                                    }
                                    catch { shotsound.Dispose(); }
                                }
                                catch { }
                        }
                    }
                    catch
                    {
                        MessageBox.Show("DirectSound initialization failed. You won`t have music...");
                        return;
                    }
                };
            new Thread(play).Start();
        }
Example #18
0
        /// <summary>
        /// Initializes a new stream player to play the specified stream containing wave data in the specified
        /// format through the specified device.
        /// </summary>
        /// <param name="playbackDevice">The device through which playback is to occur.</param>
        /// <param name="format">The format of the wave data in the stream.</param>
        /// <param name="stream">The stream of wave data to play.</param>
        public StreamPlayer(Device playbackDevice, WaveFormat format, Stream stream)
        {
            _playbackDevice = playbackDevice;
            _format = format;
            _stream = stream;

            BufferDescription bufferDescription = new BufferDescription(format);
            bufferDescription.BufferBytes = format.AverageBytesPerSecond;
            bufferDescription.ControlVolume = true;
            bufferDescription.GlobalFocus = true;

            _buffer = new SecondaryBuffer(bufferDescription, playbackDevice);
            _bufferLength = _buffer.Caps.BufferBytes;

            _feedTimer = new Timer();
            _feedTimer.Interval = 250;
            _feedTimer.Tick += new EventHandler(FeedTimer_Tick);
        }
Example #19
0
 private void Init()
 {
     addbuffer = new byte[ADDBUFFERSIZE];
     
     // prepare for streaming audio
     WaveFormat format = new WaveFormat();
     short bytesPersample = 2;
     format.BitsPerSample = 16;
     format.Channels = 1;
     format.BlockAlign = bytesPersample; 
     format.FormatTag = WaveFormatTag.Pcm;
     format.SamplesPerSecond = 44100;
     format.AverageBytesPerSecond = format.SamplesPerSecond * bytesPersample;
     
     BufferDescription desc = new BufferDescription(format);
     desc.DeferLocation = true;
     desc.BufferBytes = BUFFERSIZE;
     bufferstream = new SecondaryBuffer(desc, deviceSound);
 }
Example #20
0
        public void Play()
        {
            if (_mStream == null) return;

            _mStream.Seek(0, SeekOrigin.Begin);

            if (_loop)
            {
                if (_bufferList.Count == 0)
                    _bufferList.Add(new SecondaryBuffer(_mStream, new BufferDescription { BufferBytes = (int)_mStream.Length, ControlVolume = true }, SoundManager.Device) { Volume = SoundManager.Vol });
                else if (_bufferList[0] == null || _bufferList[0].Disposed)
                    _bufferList[0] = new SecondaryBuffer(_mStream, new BufferDescription { BufferBytes = (int)_mStream.Length, ControlVolume = true }, SoundManager.Device) { Volume = SoundManager.Vol };

                if (!_bufferList[0].Status.Playing)
                    _bufferList[0].Play(0, BufferPlayFlags.Looping);
            }
            else
            {
                for (int i = _bufferList.Count - 1; i >= 0; i--)
                {
                    if (_bufferList[i] == null || _bufferList[i].Disposed)
                    {
                        _bufferList.RemoveAt(i);
                        continue;
                    }

                    if (!_bufferList[i].Status.Playing)
                    {
                        _bufferList[i].Play(0, BufferPlayFlags.Default);
                        return;
                    }
                }

                if (_bufferList.Count >= Settings.SoundOverLap) return;

                SecondaryBuffer buffer = new SecondaryBuffer(_mStream, new BufferDescription { BufferBytes = (int)_mStream.Length, ControlVolume = true }, SoundManager.Device) { Volume = SoundManager.Vol };
                buffer.Play(0, BufferPlayFlags.Default);
                _bufferList.Add(buffer);
            }

        }
Example #21
0
        public void PlaySound(Stream EmbeddedSoundStream, bool Loop)
        {
            try
            {
                _soundBuffer = new SecondaryBuffer(EmbeddedSoundStream, _bufferDesc, _soundDevice);
                _buffer3D = new Buffer3D(_soundBuffer);
                if (Loop)
                {
                    _soundBuffer.Play(0, BufferPlayFlags.Looping);
                }
                else
                {

                    _soundBuffer.Play(0, BufferPlayFlags.Default);
                }
            }
            catch (Exception expPlay)
            {
                Console.WriteLine(expPlay.Message);
            }
        }
Example #22
0
        internal MdxSound(Device device, string filename, bool is3d)
        {
            BufferDescription desc = new BufferDescription();

            if (is3d)
            {
                desc.Control3D = true;
                desc.Guid3DAlgorithm = DSoundHelper.Guid3DAlgorithmDefault;
                desc.Mute3DAtMaximumDistance = true;
            }
            desc.ControlVolume = true;
            desc.ControlFrequency = true;
            _buffer = new SecondaryBuffer(filename, desc, device);

            if (is3d)
            {
                _buffer3d = new Buffer3D(_buffer);
                _buffer3d.Mode = Mode3D.Normal;
                _is3d = true;
            }
        }
Example #23
0
        public StreamingPlayer(Control owner, Device device, Microsoft.DirectX.DirectSound.WaveFormat format)
        {
            m_Device = device;
            if (m_Device == null)
            {
                m_Device = new Device();
                m_Device.SetCooperativeLevel(owner, CooperativeLevel.Normal);
                m_OwnsDevice = true;
            }

            BufferDescription desc = new BufferDescription(format);
            desc.BufferBytes = format.AverageBytesPerSecond;
            desc.ControlVolume = true;
            desc.GlobalFocus = true;

            m_Buffer = new SecondaryBuffer(desc, m_Device);
            m_BufferBytes = m_Buffer.Caps.BufferBytes;

            m_Timer = new System.Timers.Timer(BytesToMs(m_BufferBytes) / 6);
            m_Timer.Enabled = false;
            m_Timer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
        }
Example #24
0
        public void PlaySound(string FullResourceName, bool Loop)
        {
            try
            {
                Stream strmTemp = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(FullResourceName);
                _soundBuffer = new SecondaryBuffer(strmTemp, _bufferDesc, _soundDevice);
                _buffer3D = new Buffer3D(_soundBuffer);
                if (Loop)
                {
                    _soundBuffer.Play(0, BufferPlayFlags.Looping);
                }
                else
                {

                    _soundBuffer.Play(0, BufferPlayFlags.Default);
                }
            }
            catch (Exception expPlay)
            {
                Console.WriteLine(expPlay.Message);
            }
        }
Example #25
0
        private void InicializeCaptureSound()
        {
            device = new Device();
            //device.SetCooperativeLevel(this, CooperativeLevel.Normal);

            //CaptureDevicesCollection captureDeviceCollection = new CaptureDevicesCollection();
            //capture = new Capture(captureDeviceCollection[0].DriverGuid);
            //DeviceInformation deviceInfo = (DeviceInformation) cmbRecordDevices.SelectedItem;  //captureDeviceCollection[0];
            capture = new Capture(record_source);

            SetWaveFormat();

            captureBufferDescription = new CaptureBufferDescription();
            captureBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond / 5;//approx 200 milliseconds of PCM data.
            captureBufferDescription.Format = waveFormat;

            playbackBufferDescription = new BufferDescription();
            playbackBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond / 5;
            playbackBufferDescription.Format = waveFormat;

            playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);
            bufferSize = captureBufferDescription.BufferBytes;
        }
Example #26
0
        /// <summary>
        /// Carga un archivo WAV de audio, indicando el volumen del mismo
        /// </summary>
        /// <param name="soundPath">Path del archivo WAV</param>
        /// <param name="volume">Volumen del mismo</param>
        public void loadSound(string soundPath, int volume)
        {
            try
            {
                dispose();

                BufferDescription bufferDescription = new BufferDescription();
                if (volume != -1)
                {
                    bufferDescription.ControlVolume = true;
                }

                soundBuffer = new SecondaryBuffer(soundPath, bufferDescription, GuiController.Instance.DirectSound.DsDevice);

                if (volume != -1)
                {
                    soundBuffer.Volume = volume;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error al cargar sonido estático WAV: " + soundPath, ex);
            }
        }
Example #27
0
		public override void play( string file, bool isName )
		{
			if ( isName )
				path = platformSpec.main.appPath + "\\sounds\\" + path;

			if ( working ) 
				try
				{
					file = System.IO.Path.GetDirectoryName( System.Windows.Forms.Application.ExecutablePath ) + "\\" + file;
					applicationBuffer = new SecondaryBuffer( file, applicationDevice );
					applicationBuffer.Volume = -1000;
					applicationBuffer.Play( 0, BufferPlayFlags.Default );
				}
				catch ( Exception e )
				{
					System.Windows.Forms.MessageBox.Show(
						e.Message,
						"erreur"
						);

					if ( e != System.IO.FileNotFoundException )
						working = false;
				}
		}
Example #28
0
        public void playbytes(Byte[] soundbytes, int bitsPerSample, int sampleRate)
        {
            int bytesPerSample;
            if (bitsPerSample == 8) bytesPerSample = 1;
            else if (bitsPerSample == 16) bytesPerSample = 2;
            else throw new NotSupportedException("Supports 8bit or 16bit");

            WaveFormat format = new WaveFormat();
            format.BitsPerSample = (short)bitsPerSample;
            format.Channels = 1;
            format.BlockAlign = (short)bytesPerSample;

            format.FormatTag = WaveFormatTag.Pcm;
            format.SamplesPerSecond = sampleRate; //sampling frequency of your data;   
            format.AverageBytesPerSecond = format.SamplesPerSecond * bytesPerSample;

            BufferDescription desc = new BufferDescription(format);
            desc.DeferLocation = true;
            desc.BufferBytes = soundbytes.Length;

            SecondaryBuffer currentBuffer = new SecondaryBuffer(desc, deviceSound);
            currentBuffer.Write(0, soundbytes, LockFlag.EntireBuffer);
            currentBuffer.Play(0, BufferPlayFlags.Default);
        }
Example #29
0
 public virtual void Dispose()
 {
     m_SecondaryBuffer.Dispose();
     m_SecondaryBuffer = null;
     m_Disposed        = true;
 }
Example #30
0
        void InitPlay(long lStartPosition, long lEndPosition)
        {
            {
                // Adjust the start and end position according to frame size
                lStartPosition = Calc.AdaptToFrame(lStartPosition, m_Asset.FrameSize);
                lEndPosition   = Calc.AdaptToFrame(lEndPosition, m_Asset.FrameSize);
                m_SamplingRate = m_Asset.SampleRate;

                // lEndPosition = 0 means that file is played to end
                if (lEndPosition != 0)
                {
                    m_lLength = (lEndPosition) - lStartPosition;
                }
                else
                {
                    m_lLength = (m_Asset.SizeInBytes - lStartPosition);
                }

                WaveFormat newFormat = new WaveFormat();
                BufferDesc = new BufferDescription();

                // retrieve format from file
                m_FrameSize = m_Asset.FrameSize;
                m_Channels  = m_Asset.Channels;
                newFormat.AverageBytesPerSecond = m_Asset.SampleRate * m_Asset.FrameSize;
                newFormat.BitsPerSample         = Convert.ToInt16(m_Asset.BitDepth);
                newFormat.BlockAlign            = Convert.ToInt16(m_Asset.FrameSize);
                newFormat.Channels = Convert.ToInt16(m_Asset.Channels);

                newFormat.FormatTag = WaveFormatTag.Pcm;

                newFormat.SamplesPerSecond = m_Asset.SampleRate;

                // loads  format to buffer description
                BufferDesc.Format = newFormat;

                // calculate size of buffer so as to contain 1 second of audio
                m_SizeBuffer = m_Asset.SampleRate * m_Asset.FrameSize;
                if (m_SizeBuffer > m_lLength)
                {
                    m_SizeBuffer = Convert.ToInt32(m_lLength);
                }

                m_RefreshLength = (m_Asset.SampleRate / 2) * m_Asset.FrameSize;
// calculate the size of VuMeter Update array length
                m_UpdateVMArrayLength = m_SizeBuffer / 20;
                m_UpdateVMArrayLength = Convert.ToInt32(Calc.AdaptToFrame(Convert.ToInt32(m_UpdateVMArrayLength), m_FrameSize));
                arUpdateVM            = new byte [m_UpdateVMArrayLength];
// reset the VuMeter
                ob_VuMeter.Reset();

                // sets the calculated size of buffer
                BufferDesc.BufferBytes = m_SizeBuffer;

// Global focus is set to true so that the sound can be played in background also
                BufferDesc.GlobalFocus = true;

                // initialising secondary buffer
                SoundBuffer = new SecondaryBuffer(BufferDesc, SndDevice);

// Compensate played length due to the skip of frames during compression
                if (m_Step != 1)
                {
                    m_CompAddition = (m_RefreshLength * 2) / m_Step;
                    m_CompAddition = Convert.ToInt32(Calc.AdaptToFrame(m_CompAddition, m_FrameSize));
                }

// Load from file to memory
                LoadStream(true);

                // check for fast play
                int reduction = 0;
                if (m_FastPlay == false)
                {
                    SoundBuffer.Write(0, m_MemoryStream, m_SizeBuffer, 0);
                }
                else
                {
                    // for fast play buffer is filled in parts with new part overlapping previous part
                    for (int i = 0; i < m_SizeBuffer; i = i + (m_Step * m_FrameSize))
                    {
                        SoundBuffer.Write(i, m_MemoryStream, m_Step * m_FrameSize, 0);
                        i = i - (2 * m_FrameSize);
                        // compute the difference in bytes skipped
                        reduction = reduction + (2 * m_FrameSize);
                    }
                }
                // Adds the length (count) of file played into a variable
                m_lPlayed = m_SizeBuffer + reduction + (2 * m_CompAddition);


                m_PlayFile = true;

// trigger  events
                StateChanged ob_StateChanged = new StateChanged(m_State);
                m_State = AudioPlayerState.Playing;
                TriggerStateChangedEvent(ob_StateChanged);
                // starts playing
                SoundBuffer.Play(0, BufferPlayFlags.Looping);
                m_BufferCheck = 1;

                //initialise and start thread for refreshing buffer
                RefreshThread = new Thread(new ThreadStart(RefreshBuffer));
                RefreshThread.Start();

// end of playing check
            }
            // end of function
        }
Example #31
0
        private void MainForm_KeyDown(object sender, KeyEventArgs e)
        {
            e.SuppressKeyPress = true;

            if (tetrisGame.GameOver || tetrisGame.Paused)
            {
                return;
            }

            if (e.KeyData == Keys.Left || e.KeyData == Keys.A)
            {
                gameField.Move(Direction.Left);
                if (sound)
                {
                    secBuffer = new SecondaryBuffer(Properties.Resources.move, secDev); //创建辅助缓冲区
                    secBuffer.Play(0, BufferPlayFlags.Default);                         //设置缓冲区为默认播放
                }
            }
            if (e.KeyData == Keys.Right || e.KeyData == Keys.D)
            {
                gameField.Move(Direction.Right);
                if (sound)
                {
                    secBuffer = new SecondaryBuffer(Properties.Resources.move, secDev); //创建辅助缓冲区
                    secBuffer.Play(0, BufferPlayFlags.Default);                         //设置缓冲区为默认播放
                }
            }
            if (e.KeyData == Keys.Up || e.KeyData == Keys.W)
            {
                if (gameField.Drop())
                {
                    SetScore(tetrisGame.Score + 5);
                    if (sound)
                    {
                        secBuffer = new SecondaryBuffer(Properties.Resources.collided, secDev); //创建辅助缓冲区
                        secBuffer.Play(0, BufferPlayFlags.Default);                             //设置缓冲区为默认播放
                    }
                }
            }
            if (e.KeyData == Keys.Down || e.KeyData == Keys.S)
            {
                if (gameField.Move(Direction.Down))
                {
                    SetScore(tetrisGame.Score + 1);
                    if (sound)
                    {
                        secBuffer = new SecondaryBuffer(Properties.Resources.down, secDev); //创建辅助缓冲区
                        secBuffer.Play(0, BufferPlayFlags.Default);                         //设置缓冲区为默认播放
                    }
                }
            }
            if (e.KeyData == Keys.Space)
            {
                gameField.RotateTetromino();
                if (sound)
                {
                    secBuffer = new SecondaryBuffer(Properties.Resources.rotate, secDev); //创建辅助缓冲区
                    secBuffer.Play(0, BufferPlayFlags.Default);                           //设置缓冲区为默认播放
                }
            }

            if (e.KeyData == Keys.Q)
            {
                if (!tetrisGame.TetrominoChanged && gameField.IsTetrominoFalling)
                {
                    tetrisGame.NextTetromino = new Tetromino(gameField.ChangeTetromino(tetrisGame.NextTetromino).Type);
                    nextTetromino.Clear();
                    nextTetromino.DrawTetromino(tetrisGame.NextTetromino.MoveTo(1, 1), false);
                    tetrisGame.TetrominoChanged = true;
                    if (sound)
                    {
                        secBuffer = new SecondaryBuffer(Properties.Resources.exchange, secDev); //创建辅助缓冲区
                        secBuffer.Play(0, BufferPlayFlags.Default);                             //设置缓冲区为默认播放
                    }
                    if (tetrisGame.NextTetromino == Tetromino.Zero)
                    {
                        OnGameOver();
                    }
                }
                if (tetrisGame.TetrominoChanged)
                {
                    ShowTips(0);
                }
            }
            Refresh();
        }
        /*
         * Receive audio data coming on port 1550 and feed it to the speakers to be played.
         */
        private void Receive()
        {
            try
            {
                bStop = false;
                IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);

                while (!bStop)
                {
                    //Receive data.
                    byte[] byteData = udpClient.Receive(ref remoteEP);

                    //G711 compresses the data by 50%, so we allocate a buffer of double
                    //the size to store the decompressed data.
                    byte[] byteDecodedData = new byte[byteData.Length * 2];

                    //Decompress data using the proper vocoder.
                    if (vocoder == Vocoder.ALaw)
                    {
                        ALawDecoder.ALawDecode(byteData, out byteDecodedData);
                    }
                    else if (vocoder == Vocoder.uLaw)
                    {
                        MuLawDecoder.MuLawDecode(byteData, out byteDecodedData);
                    }
                    else
                    {
                        byteDecodedData = new byte[byteData.Length];
                        byteDecodedData = byteData;
                    }

                    //Play the data received to the user.
                    playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);
                    playbackBuffer.Write(0, byteDecodedData, LockFlag.None);
                    playbackBuffer.Play(0, BufferPlayFlags.Default);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "VoiceChat-Receive ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                nUdpClientFlag += 1;
            }
        }
        /*
         * Initializes all the data members.
         */
        private void Initialize()
        {
            try
            {
                device = new Device();
                device.SetCooperativeLevel(this, CooperativeLevel.Normal);

                CaptureDevicesCollection captureDeviceCollection = new CaptureDevicesCollection();

                DeviceInformation deviceInfo = captureDeviceCollection[0];

                capture = new Capture(deviceInfo.DriverGuid);

                short channels = 1; //Stereo.
                short bitsPerSample = 16; //16Bit, alternatively use 8Bits.
                int samplesPerSecond = 22050; //11KHz use 11025 , 22KHz use 22050, 44KHz use 44100 etc.

                //Set up the wave format to be captured.
                waveFormat = new WaveFormat();
                waveFormat.Channels = channels;
                waveFormat.FormatTag = WaveFormatTag.Pcm;
                waveFormat.SamplesPerSecond = samplesPerSecond;
                waveFormat.BitsPerSample = bitsPerSample;
                waveFormat.BlockAlign = (short)(channels * (bitsPerSample / (short)8));
                waveFormat.AverageBytesPerSecond = waveFormat.BlockAlign * samplesPerSecond;

                captureBufferDescription = new CaptureBufferDescription();
                captureBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond / 5;//approx 200 milliseconds of PCM data.
                captureBufferDescription.Format = waveFormat;

                playbackBufferDescription = new BufferDescription();
                playbackBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond / 5;
                playbackBufferDescription.Format = waveFormat;
                playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);

                bufferSize = captureBufferDescription.BufferBytes;

                bIsCallActive = false;
                nUdpClientFlag = 0;

                //Using UDP sockets
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                EndPoint ourEP = new IPEndPoint(IPAddress.Any, 1450);
                //Listen asynchronously on port 1450 for coming messages (Invite, Bye, etc).
                clientSocket.Bind(ourEP);

                //Receive data from any IP.
                EndPoint remoteEP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0));

                byteData = new byte[1024];
                //Receive data asynchornously.
                clientSocket.BeginReceiveFrom(byteData,
                                           0, byteData.Length,
                                           SocketFlags.None,
                                           ref remoteEP,
                                           new AsyncCallback(OnReceive),
                                           null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "VoiceChat-Initialize ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #34
0
    bool OpenSoundFile()
    {
        //-----------------------------------------------------------------------------
        // Name: OnOpenSoundFile()
        // Desc: Called when the user requests to open a sound file
        //-----------------------------------------------------------------------------

        OpenFileDialog ofd             = new OpenFileDialog();
        Guid           guid3DAlgorithm = Guid.Empty;

        // Get the default media path (something like C:\WINDOWS\MEDIA)
        if (string.Empty == Path)
        {
            Path = Environment.SystemDirectory.Substring(0, Environment.SystemDirectory.LastIndexOf("\\")) + "\\media";
        }

        ofd.DefaultExt       = ".wav";
        ofd.Filter           = "Wave Files|*.wav|All Files|*.*";
        ofd.FileName         = FileName;
        ofd.InitialDirectory = Path;

        if (null != applicationBuffer)
        {
            applicationBuffer.Stop();
            applicationBuffer.SetCurrentPosition(0);
        }

        // Update the UI controls to show the sound as loading a file
        buttonPlay.Enabled = buttonStop.Enabled = false;
        labelStatus.Text   = "Loading file...";

        // Display the OpenFileName dialog. Then, try to load the specified file
        if (DialogResult.Cancel == ofd.ShowDialog(this))
        {
            labelStatus.Text      = "Load aborted.";
            timerMovement.Enabled = true;
            return(false);
        }
        FileName = ofd.FileName;
        Path     = ofd.FileName.Substring(0, ofd.FileName.LastIndexOf("\\"));

        // Free any previous sound, and make a new one
        if (null != applicationBuffer)
        {
            applicationBuffer.Dispose();
            applicationBuffer = null;
        }

        // Get the software DirectSound3D emulation algorithm to use
        // Ask the user for this sample, so display the algorithm dialog box.
        AlgorithmForm frm = new AlgorithmForm();

        if (DialogResult.Cancel == frm.ShowDialog(this))
        {
            // User canceled dialog box
            labelStatus.Text   = "Load aborted.";
            labelFilename.Text = string.Empty;
            return(false);
        }

        LoadSoundFile(ofd.FileName);
        if (null == applicationBuffer)
        {
            return(false);
        }

        // Get the 3D buffer from the secondary buffer
        try
        {
            applicationBuffer3D = new Buffer3D(applicationBuffer);
        }
        catch (DirectXException)
        {
            labelStatus.Text   = "Could not get 3D buffer.";
            labelFilename.Text = string.Empty;
            return(false);
        }

        // Get the 3D buffer parameters
        application3DSettings = applicationBuffer3D.AllParameters;

        // Set new 3D buffer parameters
        application3DSettings.Mode        = Mode3D.HeadRelative;
        applicationBuffer3D.AllParameters = application3DSettings;

        if (true == applicationBuffer.Caps.LocateInHardware)
        {
            labelStatus.Text = "File loaded using hardware mixing.";
        }
        else
        {
            labelStatus.Text = "File loaded using software mixing.";
        }

        // Update the UI controls to show the sound as the file is loaded
        labelFilename.Text = FileName;
        EnablePlayUI(true);

        // Remember the file for next time
        if (null != applicationBuffer3D)
        {
            FileName = ofd.FileName;
        }
        Path = FileName.Substring(0, FileName.LastIndexOf("\\"));

        // Set the slider positions
        SetSlidersPos(0.0f, 0.0f, maxOrbitRadius, maxOrbitRadius * 2.0f);
        SliderChanged();
        return(true);
    }
Example #35
0
    private void LoadSoundFile(string FileName)
    {
        BufferDescription description = new BufferDescription();
        WaveFormat        wf          = new WaveFormat();

        buttonPlay.Enabled = false;
        buttonStop.Enabled = false;
        labelStatus.Text   = "Loading file...";

        description.Guid3DAlgorithm = guid3DAlgorithm;
        description.Control3D       = true;

        if (null != applicationBuffer)
        {
            applicationBuffer.Stop();
            applicationBuffer.SetCurrentPosition(0);
        }

        // Load the wave file into a DirectSound buffer
        try
        {
            applicationBuffer = new SecondaryBuffer(FileName, description, applicationDevice);
            if (applicationBuffer.NotVirtualized)
            {
                MessageBox.Show(this, "The 3D virtualization algorithm requested is not supported under this " +
                                "operating system.  It is available only on Windows 2000, Windows ME, and Windows 98 with WDM " +
                                "drivers and beyond. This buffer was created without virtualization.", "DirectSound Sample", MessageBoxButtons.OK);
            }
        }
        catch (ArgumentException)
        {
            // Check to see if it was a stereo buffer that threw the exception.
            labelStatus.Text   = "Wave file must be mono for 3D control.";
            labelFilename.Text = string.Empty;
            return;
        }
        catch
        {
            // Unknown error, but not a critical failure, so just update the status
            labelStatus.Text = "Could not create sound buffer.";
            return;
        }

        if (WaveFormatTag.Pcm != (WaveFormatTag.Pcm & description.Format.FormatTag))
        {
            labelStatus.Text = "Wave file must be PCM for 3D control.";
            if (null != applicationBuffer)
            {
                applicationBuffer.Dispose();
            }
            applicationBuffer = null;
        }

        // Remember the file for next time
        if (null != applicationBuffer)
        {
            FileName = FileName;
        }

        labelStatus.Text   = "Ready.";
        labelFilename.Text = FileName;
    }
Example #36
0
 private void PlayFile(FileInfo FI)
 {
     lock (this) {
         if (this.AudioDevice == null)
         {
             this.AudioDevice = new Device();
             AudioDevice.SetCooperativeLevel(this, CooperativeLevel.Normal);
         }
         this.StopPlayback();
         WaveFormat fmt = new WaveFormat();
         fmt.FormatTag             = WaveFormatTag.Pcm;
         fmt.Channels              = FI.AudioFile.Channels;
         fmt.SamplesPerSecond      = FI.AudioFile.SampleRate;
         fmt.BitsPerSample         = 16;
         fmt.BlockAlign            = (short)(FI.AudioFile.Channels * (fmt.BitsPerSample / 8));
         fmt.AverageBytesPerSecond = fmt.SamplesPerSecond * fmt.BlockAlign;
         BufferDescription BD = new BufferDescription(fmt);
         BD.BufferBytes = this.AudioBufferSize;
         BD.GlobalFocus = true;
         BD.StickyFocus = true;
         if (this.chkBufferedPlayback.Checked)
         {
             BD.ControlPositionNotify = true;
             this.CurrentBuffer       = new SecondaryBuffer(BD, this.AudioDevice);
             if (this.AudioUpdateTrigger == null)
             {
                 this.AudioUpdateTrigger = new AutoResetEvent(false);
             }
             int ChunkSize = this.AudioBufferSize / this.AudioBufferMarkers;
             BufferPositionNotify[] UpdatePositions = new BufferPositionNotify[this.AudioBufferMarkers];
             for (int i = 0; i < this.AudioBufferMarkers; ++i)
             {
                 UpdatePositions[i] = new BufferPositionNotify();
                 UpdatePositions[i].EventNotifyHandle = this.AudioUpdateTrigger.SafeWaitHandle.DangerousGetHandle();
                 UpdatePositions[i].Offset            = ChunkSize * i;
             }
             Notify N = new Notify(this.CurrentBuffer);
             N.SetNotificationPositions(UpdatePositions);
             this.CurrentStream = FI.AudioFile.OpenStream();
             this.CurrentBuffer.Write(0, this.CurrentStream, this.CurrentBuffer.Caps.BufferBytes, LockFlag.EntireBuffer);
             if (this.CurrentStream.Position < this.CurrentStream.Length)
             {
                 this.AudioUpdateTrigger.Reset();
                 this.AudioUpdateThread = new Thread(new ThreadStart(this.AudioUpdate));
                 this.AudioUpdateThread.Start();
                 this.btnPause.Enabled = true;
                 this.btnStop.Enabled  = true;
                 this.AudioIsLooping   = true;
             }
             else
             {
                 this.CurrentStream.Close();
                 this.CurrentStream  = null;
                 this.AudioIsLooping = false;
             }
         }
         else
         {
             this.CurrentStream    = FI.AudioFile.OpenStream(true);
             this.CurrentBuffer    = new SecondaryBuffer(this.CurrentStream, BD, this.AudioDevice);
             this.btnPause.Enabled = true;
             this.btnStop.Enabled  = true;
         }
         this.CurrentBuffer.Play(0, (this.AudioIsLooping ? BufferPlayFlags.Looping : BufferPlayFlags.Default));
     }
 }
Example #37
0
        private static void PlayThread(object osn)
        {
            EmulatorForm myform = (EmulatorForm)osn;

            SecondaryBuffer SecBuf;
            AutoResetEvent  SecBufNotifyAtHalf      = new AutoResetEvent(false);
            AutoResetEvent  SecBufNotifyAtBeginning = new AutoResetEvent(false);

            int SamplingRate        = (int)myform._samplingRate;
            int HoldThisManySamples = (int)(1 * SamplingRate);
            int BlockAlign          = 2;
            int SecBufByteSize      = HoldThisManySamples * BlockAlign;

            WaveFormat MyWaveFormat = new WaveFormat();

            // Set the format
            MyWaveFormat.AverageBytesPerSecond = (int)(myform._samplingRate * BlockAlign);
            MyWaveFormat.BitsPerSample         = (short)16;
            MyWaveFormat.BlockAlign            = (short)BlockAlign;
            MyWaveFormat.Channels         = (short)1;
            MyWaveFormat.SamplesPerSecond = (int)myform._samplingRate;
            MyWaveFormat.FormatTag        = WaveFormatTag.Pcm;

            BufferDescription MyDescription;

            // Set BufferDescription
            MyDescription = new BufferDescription();

            MyDescription.Format                = MyWaveFormat;
            MyDescription.BufferBytes           = HoldThisManySamples * BlockAlign;
            MyDescription.CanGetCurrentPosition = true;
            MyDescription.ControlPositionNotify = true;
            MyDescription.GlobalFocus           = true;

            // Create the buffer
            SecBuf = new SecondaryBuffer(MyDescription, myform._directSoundDevice);

            Notify MyNotify;

            MyNotify = new Notify(SecBuf);

            BufferPositionNotify[] MyBufferPositions = new BufferPositionNotify[2];

            MyBufferPositions[0].Offset            = 0;
            MyBufferPositions[0].EventNotifyHandle = SecBufNotifyAtBeginning.Handle;
            MyBufferPositions[1].Offset            = (HoldThisManySamples / 2) * BlockAlign;
            MyBufferPositions[1].EventNotifyHandle = SecBufNotifyAtHalf.Handle;

            MyNotify.SetNotificationPositions(MyBufferPositions);

            WaitHandle[] SecBufWaitHandles = { SecBufNotifyAtBeginning, SecBufNotifyAtHalf };

            Int16[] buffer;

            buffer = myform._sn.GenerateSamples((uint)HoldThisManySamples, "");
            SecBuf.Write(0, buffer, LockFlag.None);
            SecBuf.Play(0, BufferPlayFlags.Looping);

            int SecBufNextWritePosition = 0;

            while (myform._bufferPlaying)
            {
                int WriteCount    = 0,
                    PlayPosition  = SecBuf.PlayPosition,
                    WritePosition = SecBuf.WritePosition;

                if (SecBufNextWritePosition < PlayPosition &&
                    (WritePosition >= PlayPosition || WritePosition < SecBufNextWritePosition))
                {
                    WriteCount = PlayPosition - SecBufNextWritePosition;
                }
                else if (SecBufNextWritePosition > WritePosition &&
                         WritePosition >= PlayPosition)
                {
                    WriteCount = (SecBufByteSize - SecBufNextWritePosition) + PlayPosition;
                }
                // System.Diagnostics.Debug.WriteLine("WC: "+WriteCount.ToString());
                if (WriteCount > 0)
                {
                    WriteCount = (int)Math.Min(WriteCount, 1000);

                    buffer = myform._sn.GenerateSamples((uint)WriteCount / 2, "");

                    SecBuf.Write(
                        SecBufNextWritePosition,
                        buffer,
                        LockFlag.None);

                    SecBufNextWritePosition = (SecBufNextWritePosition + WriteCount) % SecBufByteSize;
                }
                else
                {
                    WaitHandle.WaitAny(SecBufWaitHandles, new TimeSpan(0, 0, 5), true);
                }
            }

            SecBuf.Dispose();
            MyDescription.Dispose();
            MyNotify.Dispose();
        }
Example #38
0
 public GameSoundChannel(SecondaryBuffer buffer, Thing thing)
 {
     Buffer = buffer;
     Thing  = thing;
 }