Esempio n. 1
0
        protected void CreateSoundBuffer(int sampleRate, double bufferSizeSeconds)
        {
            // Buffer to use when marshalling the samples from an unmanaged pointer.
            // Give it a reasonable initial size, it will be resized dynamically if needed.
            _sampleBuffer = new short[4096];

            // Setup the directsound buffer description
            var format = new WaveFormat(sampleRate, 16, 2);
            var buffer = new SoundBufferDescription();

            buffer.Flags          = BufferFlags.GlobalFocus | BufferFlags.ControlVolume;
            buffer.BufferBytes    = (int)(format.AverageBytesPerSecond * bufferSizeSeconds);
            buffer.Format         = format;
            buffer.AlgorithmFor3D = Guid.Empty;

            // Create a sound buffer with the specified buffer description.
            _secondaryBuffer = new SecondarySoundBuffer(_directSound, buffer);

            // Get the actual buffer size so we can keep
            // track of the current/next write position.
            _bufferBytes = _secondaryBuffer.Capabilities.BufferBytes;

            // When syncing to audio, we need samples per millisecond to estimate how
            // long to sleep for when waiting for enough free space in the playback buffer.
            _samplesPerMs = format.AverageBytesPerSecond / (sizeof(short) * 1000d);
        }
Esempio n. 2
0
        public override void onTick()
        {
            if (isFinished())
            {
                fireDisposeEvent();
                return;
            }
            if (finished && performing)
            {
                //The weapon is done doing what it needs to do, but a sound is still playing.
                //Do not free this weapon until the sound is done playing.
                performing = (Hit != null && DSound.isPlaying(Hit)) || (expl != null && DSound.isPlaying(expl));
                return;
            }

            performing = true;
            base.onTick();
            playSound3d(moveSound, false, false);
            if (inFiringRange())
            {
                moveSound.Stop();
                Hit = target.loadSound(target.soundPath + "bsg" + Common.getRandom(3, 4) + ".wav");
                target.playSound(Hit, true, false);
                fireHitEvent(target, Common.getRandom(100, 200));
                finished = true;
                return;
            }

            if (!DSound.isPlaying(moveSound))
            {
                finished = true;
                explode();
                performing = (Hit != null && DSound.isPlaying(Hit)) || (expl != null && DSound.isPlaying(expl));
            }
        }
        private void InitialiseDirectSound(IntPtr windowHandle, int sampleRate)
        {
            var waveFormat = new WaveFormat(sampleRate, 16, 2);

            _directSound = new DirectSound();
            _directSound.SetCooperativeLevel(windowHandle, CooperativeLevel.Priority);

            var primaryBufferDescription = new SoundBufferDescription()
            {
                Flags          = BufferFlags.PrimaryBuffer,
                AlgorithmFor3D = Guid.Empty,
            };

            _primarySoundBuffer = new PrimarySoundBuffer(_directSound, primaryBufferDescription)
            {
                Format = waveFormat
            };

            _soundBufferLength = waveFormat.ConvertLatencyToByteSize(500);

            var secondaryBufferDescription = new SoundBufferDescription()
            {
                Format         = waveFormat,
                Flags          = BufferFlags.GetCurrentPosition2 | BufferFlags.GlobalFocus,
                BufferBytes    = _soundBufferLength,
                AlgorithmFor3D = Guid.Empty,
            };

            _soundBuffer = new SecondarySoundBuffer(_directSound, secondaryBufferDescription);
        }
Esempio n. 4
0
        public static void PlaySound3d(SecondarySoundBuffer Sound, bool bCloseFirst, bool bLoopSound, double x, double y, double z)
        {
            lock (playLock)
            {
                SoundBuffer3D DS3DBuffer = new SoundBuffer3D(Sound);
                //stop currently playing waves?
                if (bCloseFirst)
                {
                    Sound.Stop();
                    Sound.CurrentPosition = 0;
                }
                //set the position
                DS3DBuffer.Position = Get3DVector(x, y, z);

                //loop the sound?
                if (bLoopSound)
                {
                    Sound.Play(0, SharpDX.DirectSound.PlayFlags.Looping);
                }
                else
                {
                    Sound.Play(0, SharpDX.DirectSound.PlayFlags.None);
                }
                DS3DBuffer.Dispose();
            }             //lock
        }
Esempio n. 5
0
        public virtual void onTick()
        {
//First, need to set what object sare in range
//since this is the first ontick method.
            if (vArray == null)
            {
                vArray = Interaction.getObjectsInRange(this,
                                                       reachRange,
                                                       Interaction.RangeFlag.existing);
            }
            updateTotalDistance();
            move();
            if (Options.mode == Options.Modes.mission &&
                followTarget &&
                origTarget != null)
            {
                z = origTarget.z;
            }
            if (damage < 1)
            {
                expl = DSound.LoadSound3d(DSound.SoundPath + "\\m4-1.wav");
                DSound.PlaySound(expl, true, false);
                finished = true;
            }
        }
Esempio n. 6
0
        void InitDirectSound(Control parent)
        {
            //Create the device
            MyNesDEBUGGER.WriteLine(this, "Initializing direct sound for APU", DebugStatus.None);
            _SoundDevice = new DirectSound();
            _SoundDevice.SetCooperativeLevel(parent.Parent.Handle, CooperativeLevel.Normal);
            //Create the wav format
            WaveFormat wav = new WaveFormat();

            wav.FormatTag        = WaveFormatTag.Pcm;
            wav.SamplesPerSecond = 44100;
            wav.Channels         = (short)(STEREO ? 2 : 1);
            AD = (STEREO ? 4 : 2);//Stereo / Mono
            wav.BitsPerSample         = 16;
            wav.AverageBytesPerSecond = wav.SamplesPerSecond * wav.Channels * (wav.BitsPerSample / 8);
            wav.BlockAlignment        = (short)(wav.Channels * wav.BitsPerSample / 8);
            BufferSize = wav.AverageBytesPerSecond;
            //Description
            SoundBufferDescription des = new SoundBufferDescription();

            des.Format      = wav;
            des.SizeInBytes = BufferSize;
            //des.Flags = BufferFlags.GlobalFocus | BufferFlags.Software;
            des.Flags = BufferFlags.ControlVolume | BufferFlags.ControlFrequency | BufferFlags.ControlPan | BufferFlags.ControlEffects;
            //buffer
            DATA   = new byte[BufferSize];
            buffer = new SecondarySoundBuffer(_SoundDevice, des);
            buffer.Play(0, PlayFlags.Looping);
            //channels
            InitChannels();
            MyNesDEBUGGER.WriteLine(this, "APU OK !!", DebugStatus.Cool);
        }
Esempio n. 7
0
        private void PlaySound(Stream sound)
        {
            DirectSound ds = new DirectSound();

            ds.SetCooperativeLevel(this.Handle, CooperativeLevel.Priority);


            WaveFormat format = WaveFormat.CreateCustomFormat(
                WaveFormatEncoding.Pcm,
                44100,
                2,
                4 * 44100,
                4,
                16
                );

            SoundBufferDescription primaryDesc = new SoundBufferDescription();

            primaryDesc.Format      = format;
            primaryDesc.Flags       = BufferFlags.GlobalFocus;
            primaryDesc.BufferBytes = 8 * 4 * 44100;
            PrimarySoundBuffer pBuffer = new PrimarySoundBuffer(ds, primaryDesc);

            SoundBufferDescription secondDesc = new SoundBufferDescription();

            secondDesc.Format      = format;
            secondDesc.Flags       = BufferFlags.GlobalFocus | BufferFlags.ControlPositionNotify | BufferFlags.GetCurrentPosition2;
            secondDesc.BufferBytes = 8 * 4 * 44100;

            SecondarySoundBuffer secondBuffer = new SecondarySoundBuffer(ds, secondDesc);

            secondBuffer.Write(sound.ReadAll(), 0, LockFlags.None);
            secondBuffer.Play(0, PlayFlags.None);
        }
Esempio n. 8
0
 public override void serverSideHit(Projector target, int damageAmount)
 {
     gunHitSound = target.loadSound(target.soundPath + "gun1-" + Common.getRandom(1, 5) + ".wav");
     target.playSound(gunHitSound, true, false);
     fireHitEvent(target, damageAmount);
     finished = true;
 }
Esempio n. 9
0
        public void InitializeBuffer(int rate, int channels)
        {
            format                       = new WaveFormat();
            format.FormatTag             = WaveFormatTag.Pcm;
            format.SamplesPerSecond      = rate;
            format.BitsPerSample         = 16;
            format.Channels              = (short)channels;
            format.BlockAlignment        = (short)(format.Channels * (format.BitsPerSample / 8));
            format.AverageBytesPerSecond = format.SamplesPerSecond * format.BlockAlignment;

            BufferSize  = format.AverageBytesPerSecond;
            BufferSize += 512 - (BufferSize % 512);

            buffer = new byte[BufferSize];

            SoundBufferDescription description = new SoundBufferDescription();

            description.Format      = format;
            description.SizeInBytes = BufferSize;
            description.Flags       = BufferFlags.ControlVolume | BufferFlags.GlobalFocus | BufferFlags.ControlPositionNotify;

            sbuffer    = new SecondarySoundBuffer[2];
            sbuffer[0] = new SecondarySoundBuffer(DirectSoundWrapper.Device, description);
            sbuffer[1] = new SecondarySoundBuffer(DirectSoundWrapper.Device, description);
        }
Esempio n. 10
0
        public void Dispose()
        {
            try
            {
                Stop();
            }
            catch { }

            if (this.buffer != null)
            {
                try
                {
                    if (this.buffer.Status == BufferStatus.Playing)
                    {
                        this.buffer.Stop();
                    }
                }
                catch { }
                buffer.Dispose();
                this.buffer = null;
            }

            if (NotificationEvent != null)
            {
                NotificationEvent.Close();
                NotificationEvent = null;
            }

            this.ClearStreams();
        }
Esempio n. 11
0
		public Sound(IntPtr handle, DirectSound device)
		{
			if (device != null)
			{
				device.SetCooperativeLevel(handle, CooperativeLevel.Priority);

				var format = new WaveFormat
					{
						SamplesPerSecond = 44100,
						BitsPerSample = 16,
						Channels = 2,
						FormatTag = WaveFormatTag.Pcm,
						BlockAlignment = 4
					};
				format.AverageBytesPerSecond = format.SamplesPerSecond * format.Channels * (format.BitsPerSample / 8);

				var desc = new SoundBufferDescription
					{
						Format = format,
						Flags =
							BufferFlags.GlobalFocus | BufferFlags.Software | BufferFlags.GetCurrentPosition2 | BufferFlags.ControlVolume,
						SizeInBytes = BufferSize
					};
				DSoundBuffer = new SecondarySoundBuffer(device, desc);
				ChangeVolume(Global.Config.SoundVolume);
			}
			SoundBuffer = new byte[BufferSize];

			disposed = false;
		}
Esempio n. 12
0
        public Sound(IntPtr formHandle)
        {
            directSound = new DirectSound();
            directSound.SetCooperativeLevel(formHandle, CooperativeLevel.Normal);

            // WAVEFORMATEX Structure (from Microsoft Documentation on DirectSound)
            // https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ee419019(v%3dvs.85)
            var wFormatTag      = WaveFormatEncoding.Pcm;
            var nSamplesPerSec  = 44100;
            var nChannels       = 1;
            var wBitsPerSample  = 16;                               // (short)
            var nBlockAlign     = (nChannels * wBitsPerSample) / 8; // nBlockAlign must be equal to the product of nChannels and wBitsPerSample divided by 8 (bits per byte)
            var nAvgBytesPerSec = nSamplesPerSec * nBlockAlign;     // nAvgBytesPerSec should be equal to the product of nSamplesPerSec and nBlockAlign

            waveFormat = WaveFormat.CreateCustomFormat(
                tag: wFormatTag,
                sampleRate: nSamplesPerSec,
                channels: nChannels,
                averageBytesPerSecond: nAvgBytesPerSec,
                blockAlign: nBlockAlign,
                bitsPerSample: wBitsPerSample
                );

            var bufferDesc = new SoundBufferDescription();

            bufferDesc.Format      = waveFormat;
            bufferDesc.BufferBytes = Convert.ToInt32(
                bufferDuration.TotalSeconds * waveFormat.AverageBytesPerSecond / waveFormat.Channels);

            buffer = new SecondarySoundBuffer(directSound, bufferDesc);

            int numSamples = buffer.Capabilities.BufferBytes / waveFormat.BlockAlign;

            samples = new short[numSamples];
        }
Esempio n. 13
0
        public override void onTick()
        {
            if (isFinished())
            {
                fireDisposeEvent();
                return;
            }

            if (finished && performing)
            {
                performing = (missileHitSound != null && DSound.isPlaying(missileHitSound)) || (expl != null && DSound.isPlaying(expl));
                return;
            }

            performing = true;
            playSound3d(missileSound, false, true);
            base.onTick();
            if (inFiringRange())
            {
                missileSound.Stop();
                missileHitSound = target.loadSound(target.soundPath + "m3-" + Common.getRandom(1, 3) + ".wav");
                target.playSound(missileHitSound, true, false);
                fireHitEvent(target, Common.getRandom(300));
                finished = true;
                return;
            }
            if (totalDistance > 15.0 || finished)
            {
                missileSound.Stop();
                finished   = true;
                performing = (missileHitSound != null && DSound.isPlaying(missileHitSound)) || (expl != null && DSound.isPlaying(expl));
            }
        }
Esempio n. 14
0
        public Sound(IntPtr handle, DirectSound device)
        {
            if (device != null)
            {
                device.SetCooperativeLevel(handle, CooperativeLevel.Priority);

                var format = new WaveFormat
                {
                    SamplesPerSecond = 44100,
                    BitsPerSample    = 16,
                    Channels         = 2,
                    FormatTag        = WaveFormatTag.Pcm,
                    BlockAlignment   = 4
                };
                format.AverageBytesPerSecond = format.SamplesPerSecond * format.Channels * (format.BitsPerSample / 8);

                var desc = new SoundBufferDescription
                {
                    Format = format,
                    Flags  =
                        BufferFlags.GlobalFocus | BufferFlags.Software | BufferFlags.GetCurrentPosition2 | BufferFlags.ControlVolume,
                    SizeInBytes = BufferSize
                };
                DSoundBuffer = new SecondarySoundBuffer(device, desc);
                ChangeVolume(Global.Config.SoundVolume);
            }
            SoundBuffer = new byte[BufferSize];

            disposed = false;
        }
Esempio n. 15
0
        public override void use()
        {
            direction = weapon.creator.direction;
            int ammunitionNumber = weapon.ammunitionFor(WeaponTypes.missile) + 1;

            if (!isAI)
            {
                if (ammunitionNumber % 2 != 0)                                  //odd number means fire from right
                {
                    missileLaunchSound.Pan = (ammunitionNumber + 1) / 2 * 2500; //give 1 to ammunition number so we can divide properly; adding 1 will make it evenly divisible by 2.
                }
                else
                {
                    missileLaunchSound.Pan = ammunitionNumber / 2 * -2500;
                }
                fox = loadSound(soundPath + "fox2.wav");
                playSound(fox, true, false);
                DXInput.startFireEffect();
            }             //if !AI
            playSound(missileLaunchSound, true, false);
            if (origTarget != null)
            {
                z = origTarget.z;
                if (isAI && origTarget is Aircraft)
                {
                    ((Aircraft)origTarget).notifyOf(Notifications.missileLaunch, Degrees.getDistanceBetween(x, y, origTarget.x, origTarget.y) <= 15);
                }
            }
        }
Esempio n. 16
0
 /// <summary>
 /// Creates a new person
 /// </summary>
 /// <param name="x">Starting x coordinate</param>
 /// <param name="y">Starting y coordinate</param>
 /// <param name="damage">Starting hit points; max damage will also be set to this value</param>
 /// <param name="isAI">True if computer controlled, false otherwise</param>
 public Person(int x, int y, int damage, bool isAI)
     : base(x, y, damage, isAI)
 {
     this.isAI = isAI;
     if (juliusLevel() == 2)
     {
         missiles = new PersonMissile[1];
     }
     else if (juliusLevel() == 3)
     {
         missiles = new PersonMissile[4];
     }
     if (juliusLevel() == 3)
     {
         shootSound = loadSound("l3s.wav");
         lockSound  = loadSound("l3a.wav");
     }
     lastStunTime  = lastPunchTime = lastMissileTime = DateTime.Now;
     stopPunchTime = Common.getRandom(1, 10);
     startSeekTime = DateTime.Now;
     blockSound    = loadSound("fb.wav");
     stunSound     = loadSound("fstun.wav");
     if (!isAI)
     {
         DSound.SetCoordinates(x, 0.0, y);
     }
 }
Esempio n. 17
0
        /// <summary>
        /// Initializes a media player with the given file
        /// </summary>
        /// <param name="fileName">the file to play</param>
        /// <returns>true if successful</returns>
        private bool _setupSoundPlayer(string filename)
        {
            bool retval = false;

            soundPlayer = null;

            if ((filename.Length != 0))
            {
                try
                {
                    fileName    = filename;
                    soundPlayer = DirectSoundWrapper.CreateSoundBufferFromWave(fileName);
                    SlimDX.Multimedia.WaveStream waveFile = new SlimDX.Multimedia.WaveStream(fileName);

                    List <NotificationPosition> pos = new List <NotificationPosition>();
                    notificationPosition.Offset = (int)waveFile.Length - 1;
                    notificationPosition.Event  = new AutoResetEvent(false);

                    pos.Add(notificationPosition);
                    soundPlayer.SetNotificationPositions(pos.ToArray());
                }
                catch (Exception ex)
                {
                    logger.Error("[SoundPlayer] Error creating soundplayer: " + ex.Message);
                }

                _updateVolume(volume);

                retval = true;
            }

            return(retval);
        }
Esempio n. 18
0
        public SecondarySoundBuffer loadSound(string filename)
        {
            SecondarySoundBuffer s = null;

            System.Diagnostics.Trace.WriteLine("Loading sound " + filename);
            if (isAI && !autoPlayTarget)
            {
                if (!forceStareo)
                {
                    s = DSound.LoadSound3d(filename);
                }
                else
                {
                    s = DSound.LoadSound(filename);
                }
            }
            else             //Either this is not AI or this is autoPlayTarget
            {
                s = DSound.LoadSound(filename);
            }
            if (s == null)
            {
                System.Diagnostics.Trace.WriteLine(filename + " is a null buffer");
            }
            return(s);
        }
 public SecondarySoundBuffer Acquire(int soundId)
 {
     if (soundId < 0 || soundId >= 4096)
     {
         return(null);
     }
     return((SecondarySoundBuffer)Archives.Sound.Open <SecondarySoundBuffer>(GetFilePath(soundId), stream =>
     {
         SoundBufferDescription bufferDescription1 = new SoundBufferDescription();
         bufferDescription1.Format = _waveFormat;
         bufferDescription1.BufferBytes = checked ((int)(stream.Length - 40L));
         SoundBufferDescription bufferDescription2 = bufferDescription1;
         BufferFlags num1 = bufferDescription2.Flags | (BufferFlags)128;
         bufferDescription2.Flags = num1;
         SoundBufferDescription bufferDescription3 = bufferDescription1;
         BufferFlags num2 = bufferDescription3.Flags | (BufferFlags)32;
         bufferDescription3.Flags = num2;
         SoundBufferDescription bufferDescription4 = bufferDescription1;
         BufferFlags num3 = bufferDescription4.Flags | (BufferFlags)64;
         bufferDescription4.Flags = num3;
         SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(_soundDevice, bufferDescription1);
         stream.Seek(40L, SeekOrigin.Begin);
         byte[] buffer = new byte[stream.Length - 40L];
         stream.Read(buffer, 0, buffer.Length);
         secondarySoundBuffer.Write(buffer, 0, (SharpDX.DirectSound.LockFlags) 2);
         return secondarySoundBuffer;
     }));
 }
Esempio n. 20
0
 /// <summary>
 /// Creates a new wreckage
 /// </summary>
 /// <param name="x">The mid X value.</param>
 /// <param name="y">The mid y value.</param>
 /// <param name="damage">The damage points</param>
 /// <param name="length">The length</param>
 /// <param name="width">The width</param>
 public BurningWreckage(int x, int y, int damage, int length, int width)
     : base(x, y, damage, length, width)
 {
     hitFile   = "fwreckage.wav";
     fireSound = loadSound("ffire.wav");
     playSound(fireSound, true, true);
 }
Esempio n. 21
0
        public override void onTick()
        {
            if (isFinished())
            {
                fireDisposeEvent();
                return;
            }
            if (finished && performing)
            {
                //The weapon is done doing what it needs to do, but a sound is still playing.
                //Do not free this weapon until the sound is done playing or the program will act up.
                if (gunHitSound != null)
                {
                    performing = DSound.isPlaying(gunHitSound);
                }
                return;
            }

            performing = true;
            base.onTick();
            if (inFiringRange())
            {
                gunHitSound = target.loadSound(target.soundPath + "gun1-" + Common.getRandom(1, 5) + ".wav");
                target.playSound(gunHitSound, true, false);
                fireHitEvent(target, 10);
                finished = true;
                return;
            }

            if (totalDistance >= 4)
            {
                finished   = true;
                performing = false;
            }
        }
Esempio n. 22
0
        public DirectSound(
            Form form,
            int sampleRate,
            int bufferCount)
        {
            if ((sampleRate % 50) != 0)
            {
                throw new ArgumentOutOfRangeException("sampleRate", "Sample rate must be a multiple of 50!");
            }
            _sampleRate = sampleRate;
            var bufferSize = sampleRate / 50;

            for (int i = 0; i < bufferCount; i++)
            {
                _fillQueue.Enqueue(new uint[bufferSize]);
            }
            _bufferSize  = bufferSize;
            _bufferCount = bufferCount;
            _zeroValue   = 0;

            var hWnd = form != null ? form.Handle : IntPtr.Zero;

            _device = new DirectSound8();
            _device.SetCooperativeLevel(hWnd, DSSCL.PRIORITY);

            // we always use 16 bit stereo (uint per sample)
            const short channels      = 2;
            const short bitsPerSample = 16;
            const int   sampleSize    = 4; // channels * (bitsPerSample / 8);
            var         wf            = new WaveFormat(_sampleRate, bitsPerSample, channels);

            // Create a buffer
            var bufferDesc = new DSBUFFERDESC();

            bufferDesc.dwBufferBytes = _bufferSize * sampleSize * _bufferCount;
            bufferDesc.dwFlags       =
                DSBCAPS_FLAGS.CTRLVOLUME |
                DSBCAPS_FLAGS.CTRLPOSITIONNOTIFY |
                DSBCAPS_FLAGS.GLOBALFOCUS |
                DSBCAPS_FLAGS.GETCURRENTPOSITION2;
            bufferDesc.Format = wf;
            _soundBuffer      = new SecondarySoundBuffer(_device, bufferDesc);

            var posNotify = new DSBPOSITIONNOTIFY[_bufferCount];

            for (int i = 0; i < posNotify.Length; i++)
            {
                posNotify[i]            = new DSBPOSITIONNOTIFY();
                posNotify[i].dwOffset   = i * _bufferSize * sampleSize;
                posNotify[i].WaitHandle = _fillEvent;
            }
            _soundBuffer.SetNotificationPositions(posNotify);

            _wavePlayThread = new Thread(WavePlayThreadProc);
            _wavePlayThread.IsBackground = true;
            _wavePlayThread.Name         = "WavePlay";
            _wavePlayThread.Priority     = ThreadPriority.Highest;
            _wavePlayThread.Start();
        }
Esempio n. 23
0
 public static bool isLooping(SecondarySoundBuffer s)
 {
     if ((s.Status & (int)BufferStatus.Looping) == (int)BufferStatus.Looping)
     {
         return(true);
     }
     return(false);
 }
 void releaseResources()
 {
     if (audioBuffer != null)
     {
         delete audioBuffer;
         audioBuffer = null;
     }
 }
Esempio n. 25
0
 private void Register(SecondarySoundBuffer soundBuffer)
 {
     if (soundBuffer == null)
     {
         return;
     }
     this._buffers.Add(soundBuffer);
 }
Esempio n. 26
0
        public void StopSound()
        {
            _deviceBuffer.Stop();
            _deviceBuffer.Dispose();
            _deviceBuffer = null;

            BufferSizeSamples = 0;
        }
Esempio n. 27
0
 public override void serverSideHit(Projector target, int remainingDamage)
 {
     missileSound.Stop();
     hitSound = target.loadSound(target.soundPath + "m3-" + Common.getRandom(1, 2) + ".wav");
     target.playSound(hitSound, true, false);
     fireHitEvent(target, remainingDamage);
     finished = true;
 }
Esempio n. 28
0
 public override void serverSideHit(Projector target, int damageAmount)
 {
     missileSound.Stop();
     missileHitSound = target.loadSound(target.soundPath + "m3-" + Common.getRandom(1, 3) + ".wav");
     target.playSound(missileHitSound, true, false);
     fireHitEvent(target, damageAmount);
     finished = true;
 }
Esempio n. 29
0
 public override void playCrashSound(int x, int y)
 {
     if (crashSound == null)
     {
         crashSound = DSound.LoadSound3d(DSound.SoundPath + "\\a_fwall.wav");
     }
     DSound.PlaySound3d(crashSound, true, false, x, y, 0);
 }
Esempio n. 30
0
 protected override void ShutdownAudioFile()
 {
     if (_SecondaryBuffer != null)
     {
         _SecondaryBuffer.Dispose();
         _SecondaryBuffer = null;
     }
 }
Esempio n. 31
0
        static void Main(string[] args)
        {
            DirectSound directSound = new DirectSound();

            var form = new Form();
            form.Text = "SharpDX - DirectSound Demo";

            // Set Cooperative Level to PRIORITY (priority level can call the SetFormat and Compact methods)
            //
            directSound.SetCooperativeLevel(form.Handle, CooperativeLevel.Priority);

            // Create PrimarySoundBuffer
            var primaryBufferDesc = new SoundBufferDescription();
            primaryBufferDesc.Flags = BufferFlags.PrimaryBuffer;
            primaryBufferDesc.AlgorithmFor3D = Guid.Empty;

            var primarySoundBuffer = new PrimarySoundBuffer(directSound, primaryBufferDesc);

            // Play the PrimarySound Buffer
            primarySoundBuffer.Play(0, PlayFlags.Looping);

            // Default WaveFormat Stereo 44100 16 bit
            WaveFormat waveFormat = new WaveFormat();

            // Create SecondarySoundBuffer
            var secondaryBufferDesc = new SoundBufferDescription();
            secondaryBufferDesc.BufferBytes = waveFormat.ConvertLatencyToByteSize(60000);
            secondaryBufferDesc.Format = waveFormat;
            secondaryBufferDesc.Flags = BufferFlags.GetCurrentPosition2 | BufferFlags.ControlPositionNotify | BufferFlags.GlobalFocus |
                                        BufferFlags.ControlVolume | BufferFlags.StickyFocus;
            secondaryBufferDesc.AlgorithmFor3D = Guid.Empty;
            var secondarySoundBuffer = new SecondarySoundBuffer(directSound, secondaryBufferDesc);

            // Get Capabilties from secondary sound buffer
            var capabilities = secondarySoundBuffer.Capabilities;

            // Lock the buffer
            DataStream dataPart2;
            var dataPart1 =secondarySoundBuffer.Lock(0, capabilities.BufferBytes,  LockFlags.EntireBuffer, out dataPart2);

            // Fill the buffer with some sound
            int numberOfSamples = capabilities.BufferBytes/waveFormat.BlockAlign;
            for (int i = 0; i < numberOfSamples; i++)
            {
                double vibrato = Math.Cos(2 * Math.PI * 10.0 * i /waveFormat.SampleRate);
                short value = (short) (Math.Cos(2*Math.PI*(220.0 + 4.0 * vibrato)*i/waveFormat.SampleRate)*16384); // Not too loud
                dataPart1.Write(value);
                dataPart1.Write(value);
            }

            // Unlock the buffer
            secondarySoundBuffer.Unlock(dataPart1, dataPart2);

            // Play the song
            secondarySoundBuffer.Play(0, PlayFlags.Looping);
           
            Application.Run(form);
        }
Esempio n. 32
0
        /// <summary>
        /// Play DX7.
        /// </summary>
        /// <param name="channels">An array of values for each channel (values between 0 and 1, usually 8 channels).</param>
        public static void PlayDX7(Primitive channels)
        {
            Initialise();
            try
            {
                int i, iServo;
                double duration = 0.0225;
                int sampleCount = (int)(duration * waveFormat.SamplesPerSecond);

                // buffer description
                SoundBufferDescription soundBufferDescription = new SoundBufferDescription();
                soundBufferDescription.Format = waveFormat;
                soundBufferDescription.Flags = BufferFlags.Defer;
                soundBufferDescription.SizeInBytes = sampleCount * waveFormat.BlockAlignment;

                SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(directSound, soundBufferDescription);

                short[] rawsamples = new short[sampleCount];
                int stopSamples = (int)(0.0004 * waveFormat.SamplesPerSecond);
                List<int> servoSamples = new List<int>();
                Primitive indices = SBArray.GetAllIndices(channels);
                int servoCount = SBArray.GetItemCount(indices);
                for (iServo = 1; iServo <= servoCount; iServo++)
                {
                    servoSamples.Add((int)((0.0007 + 0.0008 * channels[indices[iServo]]) * waveFormat.SamplesPerSecond));
                }
                //Lead-in
                int leading = sampleCount - (servoCount + 1) * stopSamples - servoSamples.Sum();
                int sample = 0;
                for (i = 0; i < leading; i++) rawsamples[sample++] = 0;
                //Servos
                for (i = 0; i < stopSamples; i++) rawsamples[sample++] = (short)(-amplitude);
                for (iServo = 0; iServo < servoCount; iServo++)
                {
                    for (i = 0; i < servoSamples[iServo]; i++) rawsamples[sample++] = amplitude;
                    for (i = 0; i < stopSamples; i++) rawsamples[sample++] = (short)(-amplitude);
                }

                //load audio samples to secondary buffer
                secondarySoundBuffer.Write(rawsamples, 0, LockFlags.EntireBuffer);

                //play audio buffer
                secondarySoundBuffer.Play(0, PlayFlags.None);

                //wait to complete before returning
                while ((secondarySoundBuffer.Status & BufferStatus.Playing) != 0);

                secondarySoundBuffer.Dispose();
            }
            catch (Exception ex)
            {
                TextWindow.WriteLine(ex.Message);
            }
        }
        /// <summary>Creates a sound.</summary>
        /// <param name="samples">A byte array containing the sample data (Mono 16-bit Signed samples).</param>
        /// <param name="frequency">The sample frequency in herz.</param>
        /// <param name="soundIndex">The index of the sound.</param>
        /// <param name="speakerSound">Whether the sound is a speaker sound otherwise it is a sampled sound.</param>
        /// <returns>The Sound.</returns>
        public override SoundSystem.Sound CreateSound(byte[] samples, int frequency, int soundIndex, bool speakerSound)
        {
            WaveFormat waveFormat = new WaveFormat();
            waveFormat.FormatTag = WaveFormatTag.Pcm;
            waveFormat.Channels = (short) 1;
            waveFormat.SamplesPerSecond = frequency;
            waveFormat.BlockAlignment = (short) 2;
            waveFormat.AverageBytesPerSecond = frequency * 2;
            waveFormat.BitsPerSample = (short) 16;

            SoundBufferDescription soundBufferDescription = new SoundBufferDescription();
            soundBufferDescription.Format = waveFormat;
            soundBufferDescription.Flags = BufferFlags.ControlVolume;
            soundBufferDescription.SizeInBytes = samples.Length;

            SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(_directSound, soundBufferDescription);
            secondarySoundBuffer.Write(samples, 0, LockFlags.EntireBuffer);

            return new SlimDXSound(secondarySoundBuffer);
        }
Esempio n. 34
0
        /// <summary>
        ///   Constructs a new Audio Output Device.
        /// </summary>
        /// 
        /// <param name="device">Global identifier of the audio output device.</param>
        /// <param name="owner">The owner window handle.</param>
        /// <param name="samplingRate">The sampling rate of the device.</param>
        /// <param name="channels">The number of channels of the device.</param>
        /// 
        public AudioOutputDevice(Guid device, IntPtr owner, int samplingRate, int channels)
        {
            this.owner = owner;
            this.samplingRate = samplingRate;
            this.channels = channels;
            this.device = device;

            DirectSound ds = new DirectSound(device);
            ds.SetCooperativeLevel(owner, CooperativeLevel.Priority);


            // Set the output format
            WaveFormat waveFormat = new WaveFormat();
            waveFormat.FormatTag = WaveFormatTag.IeeeFloat;
            waveFormat.BitsPerSample = 32;
            waveFormat.BlockAlignment = (short)(waveFormat.BitsPerSample * channels / 8);
            waveFormat.Channels = (short)channels;
            waveFormat.SamplesPerSecond = samplingRate;
            waveFormat.AverageBytesPerSecond = waveFormat.SamplesPerSecond * waveFormat.BlockAlignment;

            bufferSize = 8 * waveFormat.AverageBytesPerSecond;


            // Setup the secondary buffer
            SoundBufferDescription desc2 = new SoundBufferDescription();
            desc2.Flags =
                BufferFlags.GlobalFocus |
                BufferFlags.ControlPositionNotify |
                BufferFlags.GetCurrentPosition2;
            desc2.SizeInBytes = bufferSize;
            desc2.Format = waveFormat;

            buffer = new SecondarySoundBuffer(ds, desc2);


            var list = new List<NotificationPosition>();
            int numberOfPositions = 32;

            // Set notification for buffer percentiles
            for (int i = 0; i < numberOfPositions; i++)
            {
                list.Add(new NotificationPosition()
                {
                    Event = new AutoResetEvent(false),
                    Offset = i * bufferSize / numberOfPositions + 1,
                });
            }

            // Set notification for end of buffer
            list.Add(new NotificationPosition()
            {
                Offset = bufferSize - 1,
                Event = new AutoResetEvent(false)
            });

            firstHalfBufferIndex = numberOfPositions / 2;
            secondHalfBufferIndex = numberOfPositions;

            notifications = list.ToArray();

            System.Diagnostics.Debug.Assert(notifications[firstHalfBufferIndex].Offset == bufferSize / 2 + 1);
            System.Diagnostics.Debug.Assert(notifications[secondHalfBufferIndex].Offset == bufferSize - 1);

            // Make a copy of the wait handles
            waitHandles = new WaitHandle[notifications.Length];
            for (int i = 0; i < notifications.Length; i++)
                waitHandles[i] = notifications[i].Event;

            // Store all notification positions
            buffer.SetNotificationPositions(notifications);
        }
Esempio n. 35
0
        public void Initialize(IntPtr handle)
        {
            if (isInitialized)
            {
                Dispose();
            }
            isInitialized = false;
            LoadSettings();
            //Create the device
            Console.WriteLine("DirectSound: Initializing directSound ...");
            _SoundDevice = new DirectSound();
            _SoundDevice.SetCooperativeLevel(handle, CooperativeLevel.Normal);

            //Create the wav format
            WaveFormat wav = new WaveFormat();
            wav.FormatTag = WaveFormatTag.Pcm;
            wav.SamplesPerSecond = Program.Settings.Audio_Frequency;
            wav.Channels = 1;
            wav.BitsPerSample = Program.Settings.Audio_BitsPerSample;
            wav.AverageBytesPerSecond = wav.SamplesPerSecond * wav.Channels * (wav.BitsPerSample / 8);
            wav.BlockAlignment = (short)(wav.Channels * wav.BitsPerSample / 8);

            //BufferSize = (int)(wav.AverageBytesPerSecond * ((double)Program.Settings.Audio_BufferSizeInMilliseconds) / (double)1000);
            BufferSize = Program.Settings.Audio_BufferSizeInBytes;

            //latency_in_bytes = (int)((double)wav.AverageBytesPerSecond * (double)(Program.Settings.Audio_LatencyInPrecentage / (double)1000));
            latency_in_bytes = (Program.Settings.Audio_LatencyInPrecentage * BufferSize) / 100;
            latency_in_samples = latency_in_bytes / 2;

            Console.WriteLine("DirectSound: BufferSize = " + BufferSize + " Byte");
            Console.WriteLine("DirectSound: Latency in bytes = " + latency_in_bytes + " Byte");
            //Description
            SoundBufferDescription des = new SoundBufferDescription();
            des.Format = wav;
            des.SizeInBytes = BufferSize;
            des.Flags = BufferFlags.ControlVolume | BufferFlags.ControlFrequency | BufferFlags.ControlPan | BufferFlags.Software;

            buffer = new SecondarySoundBuffer(_SoundDevice, des);
            //buffer.Play(0, PlayFlags.Looping);

            // Set volume
            SetVolume(volume);
            Console.WriteLine("DirectSound: DirectSound initialized OK.");
            isInitialized = true;

            Shutdown();
        }
Esempio n. 36
0
        void load_sound_file(ref MemoryStream sound_stream, ref WaveStream wave_stream, ref byte[] data_array, ref SoundBufferDescription buf_desc, ref SecondarySoundBuffer buf, string file, ref bool executed)
        {
            try
            {
                if ((((Form1)(form1_reference)).retrieve_resources != null) && (((Form1)(form1_reference)).retrieve_resources.EntryFileNames.Contains(file)))
                {
                    sound_stream = new MemoryStream();
                    ((Form1)(form1_reference)).retrieve_resources.Extract(file, sound_stream);
                    data_array = new byte[Convert.ToInt32(sound_stream.Length)];
                    data_array = sound_stream.ToArray();
                    wave = new WaveFormat();
                    wave.FormatTag = WaveFormatTag.Pcm;
                    wave.BitsPerSample = (short)((data_array[35] << 8) | data_array[34]);
                    wave.BlockAlignment = (short)((data_array[33] << 8) | data_array[32]);
                    wave.Channels = (short)((data_array[23] << 8) | data_array[22]);
                    wave.SamplesPerSecond = (int)((data_array[27] << 24) | (data_array[26] << 16) | (data_array[25] << 8) | (data_array[24]));
                    wave.AverageBytesPerSecond = (int)((data_array[27] << 24) | (data_array[26] << 16) | (data_array[25] << 8) | (data_array[24]));

                    sound_stream = new MemoryStream(data_array);
                    wave_stream = new WaveStream(sound_stream);
                    buf_desc = new SoundBufferDescription();
                    buf_desc.Flags = BufferFlags.GlobalFocus;
                    buf_desc.SizeInBytes = (int)sound_stream.Length;
                    buf_desc.Format = wave;
                    if (sound_stream.Length > 0)
                    {
                        buf = new SecondarySoundBuffer(device, buf_desc);
                        wave_stream.Read(data_array, 0, buf_desc.SizeInBytes);
                        buf.Write(data_array, 0, LockFlags.EntireBuffer);
                    }
                    executed = false;
                    sound_stream.Close();
                }
                else
                {
                    buf_desc = new SoundBufferDescription();
                    buf_desc.Flags = BufferFlags.GlobalFocus;
                    if (File.Exists(file))
                    {
                        wave_stream = new WaveStream(file);
                        buf_desc.Format = wave_stream.Format;
                        buf_desc.SizeInBytes = (int)wave_stream.Length;
                        data_array = new byte[wave_stream.Length];
                        buf = new SecondarySoundBuffer(device, buf_desc);
                        wave_stream.Read(data_array, 0, buf_desc.SizeInBytes);
                        buf.Write(data_array, 0, LockFlags.EntireBuffer);
                    }
                    executed = false;
                }
            }
            catch (DirectSoundException e)
            {
                MessageBox.Show(e.ToString(), "Error!", MessageBoxButtons.OK);
            }
        }
Esempio n. 37
0
        private static string _PlayWavFile(string fileName, double duration)
        {
            try
            {
                Initialise();

                WaveStream waveFile = new WaveStream(fileName);
                SoundBufferDescription soundBufferDescription = new SoundBufferDescription();
                soundBufferDescription.Format = waveFile.Format;
                soundBufferDescription.Flags = BufferFlags.Defer | BufferFlags.ControlVolume | BufferFlags.ControlPan;
                soundBufferDescription.SizeInBytes = (int)waveFile.Length;

                SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(directSound, soundBufferDescription);
                secondarySoundBuffer.Pan = pan;
                secondarySoundBuffer.Volume = volume;

                byte[] rawsamples = new byte[soundBufferDescription.SizeInBytes];
                waveFile.Read(rawsamples, 0, soundBufferDescription.SizeInBytes);
                waveFile.Close();
                secondarySoundBuffer.Write(rawsamples, 0, LockFlags.EntireBuffer);

                string name = NextName();
                Buffer buffer = new Buffer(name, secondarySoundBuffer, 0, duration);
                buffers.Add(buffer);

                Thread thread = new Thread(new ParameterizedThreadStart(DoPlay));
                thread.Start(buffer);
                if (!bAsync) thread.Join();
                return name;
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                return "";
            }
        }
Esempio n. 38
0
        public void Dispose()
        {
            isInitialized = false;
            Stop();

            buffer.Dispose(); buffer = null;
            _SoundDevice.Dispose(); _SoundDevice = null;

            GC.Collect();
        }
Esempio n. 39
0
		public void Dispose()
		{
			if (disposed) return;
			if (DSoundBuffer != null && DSoundBuffer.Disposed == false)
			{
				DSoundBuffer.Dispose();
				DSoundBuffer = null;
			}
		}
Esempio n. 40
0
        private static string _PlayWave(double frequency, double duration, Primitive waveform)
        {
            try
            {
                Initialise();
                int sampleCount = (int)(waveFormat.SamplesPerSecond / frequency);

                // buffer description
                SoundBufferDescription soundBufferDescription = new SoundBufferDescription();
                soundBufferDescription.Format = waveFormat;
                soundBufferDescription.Flags = BufferFlags.Defer | BufferFlags.ControlVolume | BufferFlags.ControlPan;
                soundBufferDescription.SizeInBytes = sampleCount * waveFormat.BlockAlignment;

                SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(directSound, soundBufferDescription);
                secondarySoundBuffer.Pan = pan;
                secondarySoundBuffer.Volume = volume;

                short[] rawsamples = new short[sampleCount];
                double frac, value;

                Primitive indices = SBArray.GetAllIndices(waveform);
                int count = SBArray.GetItemCount(waveform);
                double interval = indices[count] - indices[1];
                double[] timeFrac = new double[count];
                double[] timeValue = new double[count];
                for (int i = 1; i <= count; i++) //Normalise to interval 1;
                {
                    timeFrac[i - 1] = (indices[i] - indices[1]) / interval;
                    timeValue[i - 1] = waveform[indices[i]];
                }

                for (int i = 0; i < sampleCount; i++)
                {
                    frac = i / (double)sampleCount;
                    frac = frac - (int)frac;
                    for (int j = 0; j < count - 1; j++)
                    {
                        if (frac >= timeFrac[j] && frac <= timeFrac[j + 1])
                        {
                            value = timeValue[j] + (timeValue[j + 1] - timeValue[j]) * (frac - timeFrac[j]) / (timeFrac[j + 1] - timeFrac[j]);
                            rawsamples[i] = (short)(amplitude * value);
                            break;
                        }
                    }
                }
                secondarySoundBuffer.Write(rawsamples, 0, LockFlags.EntireBuffer);

                string name = NextName();
                Buffer buffer = new Buffer(name, secondarySoundBuffer, frequency, duration);
                buffers.Add(buffer);

                Thread thread = new Thread(new ParameterizedThreadStart(DoPlay));
                thread.Start(buffer);
                if (!bAsync) thread.Join();
                return name;
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                return "";
            }
        }
Esempio n. 41
0
        private static string _PlayHarmonics(double frequency, double duration, Primitive harmonics)
        {
            try
            {
                Initialise();
                int sampleCount = (int)(waveFormat.SamplesPerSecond / frequency);

                // buffer description
                SoundBufferDescription soundBufferDescription = new SoundBufferDescription();
                soundBufferDescription.Format = waveFormat;
                soundBufferDescription.Flags = BufferFlags.Defer | BufferFlags.ControlVolume | BufferFlags.ControlPan;
                soundBufferDescription.SizeInBytes = sampleCount * waveFormat.BlockAlignment;

                SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(directSound, soundBufferDescription);
                secondarySoundBuffer.Pan = pan;
                secondarySoundBuffer.Volume = volume;

                short[] rawsamples = new short[sampleCount];
                double frac, value;

                Primitive indices = SBArray.GetAllIndices(harmonics);
                int count = SBArray.GetItemCount(harmonics);

                for (int i = 0; i < sampleCount; i++)
                {
                    frac = i / (double)sampleCount;
                    value = System.Math.Sin(2.0 * System.Math.PI * frac);
                    for (int j = 1; j <= count; j++)
                    {
                        double harmonic = indices[j];
                        value += harmonics[harmonic] * System.Math.Sin(2.0 * System.Math.PI * harmonic * frac);
                    }
                    rawsamples[i] = (short)(amplitude * value);
                }
                secondarySoundBuffer.Write(rawsamples, 0, LockFlags.EntireBuffer);

                string name = NextName();
                Buffer buffer = new Buffer(name, secondarySoundBuffer, frequency, duration);
                buffers.Add(buffer);

                Thread thread = new Thread(new ParameterizedThreadStart(DoPlay));
                thread.Start(buffer);
                if (!bAsync) thread.Join();
                return name;
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                return "";
            }
        }
Esempio n. 42
0
        private static string _Play(double frequency, double duration, int iType)
        {
            try
            {
                Initialise();
                int sampleCount = (int)(waveFormat.SamplesPerSecond / frequency);

                // buffer description
                SoundBufferDescription soundBufferDescription = new SoundBufferDescription();
                soundBufferDescription.Format = waveFormat;
                soundBufferDescription.Flags = BufferFlags.Defer | BufferFlags.ControlVolume | BufferFlags.ControlPan;
                soundBufferDescription.SizeInBytes = sampleCount * waveFormat.BlockAlignment;

                SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(directSound, soundBufferDescription);
                secondarySoundBuffer.Pan = pan;
                secondarySoundBuffer.Volume = volume;

                short[] rawsamples = new short[sampleCount];
                double frac, value;

                switch (iType)
                {
                    case 1: //Sinusoidal
                        for (int i = 0; i < sampleCount; i++)
                        {
                            frac = i / (double)sampleCount;
                            value = System.Math.Sin(2.0 * System.Math.PI * frac);
                            rawsamples[i] = (short)(amplitude * value);
                        }
                        break;
                    case 2: //Square
                        for (int i = 0; i < sampleCount; i++)
                        {
                            frac = i / (double)sampleCount;
                            frac = frac - (int)frac;
                            value = frac < 0.5 ? -1.0 : 1.0;
                            rawsamples[i] = (short)(amplitude * value);
                        }
                        break;
                }
                secondarySoundBuffer.Write(rawsamples, 0, LockFlags.EntireBuffer);

                string name = NextName();
                Buffer buffer = new Buffer(name, secondarySoundBuffer, frequency, duration);
                buffers.Add(buffer);

                Thread thread = new Thread(new ParameterizedThreadStart(DoPlay));
                thread.Start(buffer);
                if (!bAsync) thread.Join();
                return name;
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                return "";
            }
        }
Esempio n. 43
0
 void InitDirectSound(IntPtr handle)
 {            
     //Create the device
     _SoundDevice = new DirectSound();
     _SoundDevice.SetCooperativeLevel(handle, CooperativeLevel.Priority);
     //Creat the wav format, it will be mono-44100-pcm-16bit
     //TODO: support more wave formats 
     WaveFormat wav = new WaveFormat();
     wav.FormatTag = WaveFormatTag.Pcm;
     wav.SamplesPerSecond = 44100;
     wav.Channels = 1;//mono
     wav.BitsPerSample = 16;
     wav.AverageBytesPerSecond = 88200;//wav.SamplesPerSecond * wav.Channels * (wav.BitsPerSample / 8);
     wav.BlockAlignment = 2;//(wfx.Channels * wfx.BitsPerSample / 8);
     BufferSize = 88200 * 5;
     //Description
     SoundBufferDescription des = new SoundBufferDescription();
     des.Format = wav;
     des.SizeInBytes = BufferSize;
     des.Flags = BufferFlags.GlobalFocus | BufferFlags.Software;
     //buffer
     buffer = new SecondarySoundBuffer(_SoundDevice, des);
     DATA = new byte[BufferSize];
     buffer.Play(0, PlayFlags.Looping);
     //channels
     InitChannels();
 }
Esempio n. 44
0
 public void Reset()
 {
     bufferSize = audioFormat.AverageBytesPerSecond / 10;
     sBufferDescription.Flags = BufferFlags.GlobalFocus | BufferFlags.ControlVolume | BufferFlags.GetCurrentPosition2;
     sBufferDescription.Format = audioFormat;
     sBufferDescription.SizeInBytes = bufferSize * 2;
     sBuffer = new SecondarySoundBuffer(device, sBufferDescription);
     sBuffer.Volume = FloatToDB(volume);
 }
Esempio n. 45
0
		public void StopSound()
		{
			_deviceBuffer.Stop();
			_deviceBuffer.Dispose();
			_deviceBuffer = null;

			BufferSizeSamples = 0;
		}
Esempio n. 46
0
        private static string _PlayDX7(Primitive channels)
        {
            try
            {
                Initialise();
                int i, iServo;
                double duration = 0.0225;
                int sampleCount = (int)(duration * waveFormat.SamplesPerSecond);

                // buffer description
                SoundBufferDescription soundBufferDescription = new SoundBufferDescription();
                soundBufferDescription.Format = waveFormat;
                soundBufferDescription.Flags = BufferFlags.Defer | BufferFlags.ControlVolume | BufferFlags.ControlPan;
                soundBufferDescription.SizeInBytes = sampleCount * waveFormat.BlockAlignment;

                SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(directSound, soundBufferDescription);
                secondarySoundBuffer.Pan = pan;
                secondarySoundBuffer.Volume = volume;

                short[] rawsamples = new short[sampleCount];
                int stopSamples = (int)(0.0004 * waveFormat.SamplesPerSecond);
                List<int> servoSamples = new List<int>();
                Primitive indices = SBArray.GetAllIndices(channels);
                int servoCount = SBArray.GetItemCount(indices);
                for (iServo = 1; iServo <= servoCount; iServo++)
                {
                    servoSamples.Add((int)((0.0007 + 0.0008 * channels[indices[iServo]]) * waveFormat.SamplesPerSecond));
                }
                //Lead-in
                int leading = sampleCount - (servoCount + 1) * stopSamples - servoSamples.Sum();
                int sample = 0;
                for (i = 0; i < leading; i++) rawsamples[sample++] = 0;
                //Servos
                for (i = 0; i < stopSamples; i++) rawsamples[sample++] = (short)(-amplitude);
                for (iServo = 0; iServo < servoCount; iServo++)
                {
                    for (i = 0; i < servoSamples[iServo]; i++) rawsamples[sample++] = amplitude;
                    for (i = 0; i < stopSamples; i++) rawsamples[sample++] = (short)(-amplitude);
                }
                secondarySoundBuffer.Write(rawsamples, 0, LockFlags.EntireBuffer);

                string name = NextName();
                Buffer buffer = new Buffer(name, secondarySoundBuffer, 0, -1);
                buffers.Add(buffer);

                Thread thread = new Thread(new ParameterizedThreadStart(DoPlay));
                thread.Start(buffer);
                if (!bAsync) thread.Join();
                return name;
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                return "";
            }
        }
Esempio n. 47
0
		public void StartSound()
		{
			BufferSizeSamples = Sound.MillisecondsToSamples(Global.Config.SoundBufferSizeMs);

			// 35 to 65 milliseconds depending on how big the buffer is. This is a trade-off
			// between more frequent but less severe glitches (i.e. catching underruns before
			// they happen and filling the buffer with silence) or less frequent but more
			// severe glitches. At least on my Windows 8 machines, the distance between the
			// play and write cursors can be up to 30 milliseconds, so that would be the
			// absolute minimum we could use here.
			int minBufferFullnessMs = Math.Min(35 + ((Global.Config.SoundBufferSizeMs - 60) / 2), 65);
			MaxSamplesDeficit = BufferSizeSamples - Sound.MillisecondsToSamples(minBufferFullnessMs);

			var format = new WaveFormat
				{
					SamplesPerSecond = Sound.SampleRate,
					BitsPerSample = Sound.BytesPerSample * 8,
					Channels = Sound.ChannelCount,
					FormatTag = WaveFormatTag.Pcm,
					BlockAlignment = Sound.BlockAlign,
					AverageBytesPerSecond = Sound.SampleRate * Sound.BlockAlign
				};

			var desc = new SoundBufferDescription
				{
					Format = format,
					Flags =
						BufferFlags.GlobalFocus |
						BufferFlags.Software |
						BufferFlags.GetCurrentPosition2 |
						BufferFlags.ControlVolume,
					SizeInBytes = BufferSizeBytes
				};

			_deviceBuffer = new SecondarySoundBuffer(_device, desc);

			_actualWriteOffsetBytes = -1;
			_filledBufferSizeBytes = 0;
			_lastWriteTime = 0;
			_lastWriteCursor = 0;

			_deviceBuffer.Play(0, SlimDX.DirectSound.PlayFlags.Looping);
		}
Esempio n. 48
0
 private void InitDirectSound(Control parent)
 {
     Debug.WriteLine(this, "Initializing APU ....", DebugStatus.None);
     //Create the device
     _SoundDevice = new DirectSound();
     _SoundDevice.SetCooperativeLevel(parent.Parent.Handle, CooperativeLevel.Normal);
     //Create the wav format
     var wav = new WaveFormat();
     wav.FormatTag = WaveFormatTag.Pcm;
     wav.SamplesPerSecond = 44100;
     wav.Channels = (short) (STEREO ? 2 : 1);
     AD = (STEREO ? 4 : 2); //Stereo / Mono
     wav.BitsPerSample = 16;
     wav.AverageBytesPerSecond = wav.SamplesPerSecond*wav.Channels*(wav.BitsPerSample/8);
     wav.BlockAlignment = (short) (wav.Channels*wav.BitsPerSample/8);
     BufferSize = wav.AverageBytesPerSecond;
     //Description
     var des = new SoundBufferDescription
                   {
                       Format = wav,
                       SizeInBytes = BufferSize,
                       Flags =
                           BufferFlags.ControlVolume | BufferFlags.ControlFrequency | BufferFlags.ControlPan |
                           BufferFlags.ControlEffects
                   };
     //des.Flags = BufferFlags.GlobalFocus | BufferFlags.Software;
     //buffer
     DATA = new byte[BufferSize];
     buffer = new SecondarySoundBuffer(_SoundDevice, des);
     buffer.Play(0, PlayFlags.Looping);
     //channels
     InitChannels();
     Debug.WriteLine(this, "APU initialized ok !!", DebugStatus.Cool);
 }
Esempio n. 49
0
 /// <summary>
 ///   Releases unmanaged and - optionally - managed resources
 /// </summary>
 /// 
 /// <param name="disposing"><c>true</c> to release both managed and unmanaged
 /// resources; <c>false</c> to release only unmanaged resources.</param>
 /// 
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         // free managed resources
         if (buffer != null)
         {
             buffer.Dispose();
             buffer = null;
         }
     }
 }
Esempio n. 50
0
        private static void Play(double frequency, double duration, int iType)
        {
            Initialise();
            try
            {
                int sampleCount = (int)(duration * waveFormat.SamplesPerSecond);

                // buffer description
                SoundBufferDescription soundBufferDescription = new SoundBufferDescription();
                soundBufferDescription.Format = waveFormat;
                soundBufferDescription.Flags = BufferFlags.Defer;
                soundBufferDescription.SizeInBytes = sampleCount * waveFormat.BlockAlignment;

                SecondarySoundBuffer secondarySoundBuffer = new SecondarySoundBuffer(directSound, soundBufferDescription);

                short[] rawsamples = new short[sampleCount];
                double frac, value;

                switch (iType)
                {
                    case 1: //Sinusoidal
                        for (int i = 0; i < sampleCount; i++)
                        {
                            frac = frequency * duration * i / (double)sampleCount;
                            value = System.Math.Sin(2.0 * System.Math.PI * frac);
                            rawsamples[i] = (short)(amplitude * value);
                        }
                        break;
                    case 2: //Square
                        for (int i = 0; i < sampleCount; i++)
                        {
                            frac = frequency * duration * i / (double)sampleCount;
                            frac = frac - (int)frac;
                            value = frac < 0.5 ? -1.0 : 1.0;
                            rawsamples[i] = (short)(amplitude * value);
                        }
                        break;
                }

                //load audio samples to secondary buffer
                secondarySoundBuffer.Write(rawsamples, 0, LockFlags.EntireBuffer);

                //play audio buffer
                secondarySoundBuffer.Play(0, PlayFlags.None);

                //wait to complete before returning
                while ((secondarySoundBuffer.Status & BufferStatus.Playing) != 0);

                secondarySoundBuffer.Dispose();
            }
            catch (Exception ex)
            {
                TextWindow.WriteLine(ex.Message);
            }
        }
Esempio n. 51
0
 public Buffer(string name, SecondarySoundBuffer secondarySoundBuffer, double frequency, double duration, bool bDispose = true)
 {
     this.name = name;
     this.secondarySoundBuffer = secondarySoundBuffer;
     this.frequency = frequency;
     this.duration = duration;
     this.bDispose = bDispose;
     bPlaying = true;
     bLoop = LDWaveForm.bLoop;
 }