Beispiel #1
0
        private void LoadOggFile(string fileName)
        {
            Tracer.Trace("Sound.LoadOggFile", string.Format("Loading '{0}'", fileName));
            int bufferSize = 0;

            DecodedVorbisSize(fileName, ref bufferSize);
            byte[]     tempBuffer    = new byte[bufferSize];
            int        samplesPerSec = 0;
            int        channels      = 0;
            int        result        = DecodeVorbisFile(fileName, tempBuffer, bufferSize, ref samplesPerSec, ref channels);
            WaveFormat waveFormat    = new WaveFormat();

            waveFormat.Channels              = (short)channels;
            waveFormat.BitsPerSample         = 16;
            waveFormat.SamplesPerSecond      = samplesPerSec;
            waveFormat.AverageBytesPerSecond = samplesPerSec * 2 * channels;
            waveFormat.BlockAlign            = (short)(2 * channels);
            waveFormat.FormatTag             = WaveFormatTag.Pcm;
            BufferDescription bufferDesc = new BufferDescription(waveFormat);

            bufferDesc.BufferBytes = bufferSize;
            SetDescriptionFlags(ref bufferDesc);
            //bufferDesc.Flags = BufferDescriptionFlags.ControlVolume;
            buffer = new SecondaryBuffer(bufferDesc, SoundManager.Device);
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream(tempBuffer))
            {
                buffer.Write(0, stream, bufferSize, LockFlag.EntireBuffer);
            }
            BufferLoaded();
        }
        public Listener(System.Windows.Forms.Form form, Object3D object_listening)
        {
            m_listener = object_listening;
            Sound.BufferDescription description = new Sound.BufferDescription();
            Sound.WaveFormat        fmt         = new Sound.WaveFormat();
            description.PrimaryBuffer = true;
            description.Control3D     = true;
            Sound.Buffer buff = null;

            fmt.FormatTag             = Sound.WaveFormatTag.Pcm;
            fmt.Channels              = 2;
            fmt.SamplesPerSecond      = 22050;
            fmt.BitsPerSample         = 16;
            fmt.BlockAlign            = (short)(fmt.BitsPerSample / 8 * fmt.Channels);
            fmt.AverageBytesPerSecond = fmt.SamplesPerSecond * fmt.BlockAlign;

            applicationDevice.SetCooperativeLevel(form, Sound.CooperativeLevel.Priority);

            // Get the primary buffer and set the format.
            buff        = new Buffer(description, Device);
            buff.Format = fmt;

            applicationListener = new Listener3D(buff);
            listenerParameters  = applicationListener.AllParameters;
        }
Beispiel #3
0
 public Form1(int lvl)
 {
     //Init DirectSound
     snddev = new DSound.Device();
     snddev.SetCooperativeLevel(Handle, DSound.CooperativeLevel.Priority);
     snd_phit              = new DSound.Buffer(FLD_SND + "hit.wav", snddev);
     level                 = lvl;
     Text                  = TITLE;
     Icon                  = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
     FormBorderStyle       = FormBorderStyle.FixedSingle;
     BackColor             = EGA_PALETTE[(tags + 7) % 13 + 1];
     img_splash            = new Bitmap(FLD_GFX + "main.png");
     img_game              = new Bitmap(FLD_GFX + "game.png");
     img_end               = new Bitmap(FLD_GFX + "end.png");
     BackgroundImage       = new Bitmap(img_splash);
     BackgroundImageLayout = ImageLayout.Zoom;
     gfx = Graphics.FromImage(BackgroundImage);
     gfx.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.None;
     gfx.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
     gfx.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.None;
     gfx.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
     ClientSize             = BackgroundImage.Size;
     SetStyle(
         ControlStyles.OptimizedDoubleBuffer |
         ControlStyles.AllPaintingInWmPaint |
         ControlStyles.UserPaint, true);
     rnd   = new Random();
     state = 0;
     CenterToScreen();
 }
        protected virtual void Dispose(bool disposing)
        {
            // If you need thread safety, use a lock around these
            // operations, as well as in your methods that use the resource.
            if (!m_disposed)
            {
                if (disposing)
                {
                    if (m_descriptionListener != null)
                    {
                        m_descriptionListener.Dispose();
                    }

                    if (m_primary3d != null)
                    {
                        m_primary3d.Dispose();
                    }

                    if (m_listener3d != null)
                    {
                        m_listener3d.Dispose();
                    }
                }

                m_descriptionListener = null;
                m_primary3d           = null;
                m_listener3d          = null;

                // Indicate that the instance has been disposed.
                m_disposed = true;
            }
        }
Beispiel #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SoundEffect"/> class.
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="owner"></param>
        public SoundEffect(string fileName, Control owner)
        {
            BufferDescription desc;

            desc        = new BufferDescription();
            this.device = new Device();
            this.device.SetCooperativeLevel(owner.Handle, CooperativeLevel.Normal);
            this.buffer = new Buffer(this.device, desc, fileName);
        }
Beispiel #6
0
        private void LoadWavFile(string fileName)
        {
            Tracer.Trace("Sound.LoadWavFile", string.Format("Loading '{0}'", fileName));
            BufferDescription desc = new BufferDescription();

            SetDescriptionFlags(ref desc);
            buffer = new SecondaryBuffer(fileName, desc, SoundManager.Device);
            BufferLoaded();
        }
Beispiel #7
0
 /// <summary>
 /// Cleans up resources
 /// </summary>
 public void Dispose()
 {
     SoundManager.RemoveSound(this);
     if (buffer != null)
     {
         buffer.Dispose();
         buffer = null;
     }
 }
Beispiel #8
0
    public AudioClass(Control owner)
    {
        BufferDescription desc = new BufferDescription();

        localDevice = new Device();
        localDevice.SetCooperativeLevel(owner, CooperativeLevel.Normal);

        localBuffer = new Buffer(DXUtil.FindMediaFile(null, "drumpad-bass_drum.wav"), desc, localDevice);
        audioPlayer = new Audio(DXUtil.FindMediaFile(null, "DirectX Theme.wma"));
    }
Beispiel #9
0
    Microsoft.DirectX.DirectSound.Buffer LoadFile(string filename)
    {
        Microsoft.DirectX.DirectSound.BufferDescription bufferDesc = new BufferDescription();
        bufferDesc.Flags = BufferDescriptionFlags.ControlVolume;

        Microsoft.DirectX.DirectSound.Buffer buffer;
        buffer = new Microsoft.DirectX.DirectSound.Buffer(filename, bufferDesc, soundDevice);


        return(buffer);
    }
Beispiel #10
0
        public MdxListener(Device device)
        {
            BufferDescription desc = new BufferDescription();
            desc.PrimaryBuffer = true;
            desc.Control3D = true;
            desc.Mute3DAtMaximumDistance = true;

            Microsoft.DirectX.DirectSound.Buffer buffer = new Microsoft.DirectX.DirectSound.Buffer(desc, device);
            _listener = new Listener3D(buffer);

            Orientation = Matrix.Identity;
        }
Beispiel #11
0
        public MdxListener(Device device)
        {
            BufferDescription desc = new BufferDescription();

            desc.PrimaryBuffer           = true;
            desc.Control3D               = true;
            desc.Mute3DAtMaximumDistance = true;

            Microsoft.DirectX.DirectSound.Buffer buffer = new Microsoft.DirectX.DirectSound.Buffer(desc, device);
            _listener = new Listener3D(buffer);

            Orientation = Matrix.Identity;
        }
Beispiel #12
0
        /// <summary>
        /// Проигрывает звук.
        /// </summary>
        public void Play()
        {
            Double[][] extra = new Double[oscillators.Length][];
            for (Int32 i = 0; i < oscillators.Length; i++)
            {
                switch (oscillators[i].Shape)
                {
                case Waveshape.Sine:
                    Sine(oscillators[i], out extra[i]);
                    break;

                case Waveshape.Tangent:
                    Tangent(oscillators[i], out extra[i]);
                    break;

                case Waveshape.Secant:
                    Secant(oscillators[i], out extra[i]);
                    break;

                case Waveshape.Noise:
                    Noise(oscillators[i], out extra[i]);
                    break;

                case Waveshape.WhiteNoise:
                    WhiteNoise(oscillators[i], out extra[i]);
                    break;

                case Waveshape.Square:
                    Square(oscillators[i], out extra[i]);
                    break;

                case Waveshape.Saw:
                    Saw(oscillators[i], out extra[i]);
                    break;

                case Waveshape.Triangle:
                    Triangle(oscillators[i], out extra[i]);
                    break;

                case Waveshape.Void:
                    Void(oscillators[i], out extra[i]);
                    break;
                }
            }
            Average(extra, out Double[] data);
            player = new SecondaryBuffer(new BufferDescription(), new Device());
            player.Write(0, data, LockFlag.EntireBuffer);
            player.Play(0, BufferPlayFlags.Default);
        }
Beispiel #13
0
        public TgcDirectSound()
        {
            //Crear device de DirectSound
            dsDevice = new Device();
            dsDevice.SetCooperativeLevel(GuiController.Instance.MainForm, CooperativeLevel.Normal);

            //Crear Listener3D
            BufferDescription primaryBufferDesc = new BufferDescription();
            primaryBufferDesc.Control3D = true;
            primaryBufferDesc.PrimaryBuffer = true;
            primaryBuffer = new Microsoft.DirectX.DirectSound.Buffer(primaryBufferDesc, dsDevice);
            listener3d = new Listener3D(primaryBuffer);
            listener3d.Position = new Vector3(0f, 0f, 0f);
            listener3d.Orientation = new Listener3DOrientation(new Vector3(1, 0, 0), new Vector3(0, 1, 0));
        }
Beispiel #14
0
 void PlaySound2(bool snd, int tags)
 {
     DSound.Buffer buffer;
     if (snd)
     {
         buffer = new DSound.Buffer(FLD_SND + "finish.wav", snddev);
         buffer.SetCurrentPosition((int)((1 - ((float)tags / MAX_TAGS)) * buffer.Caps.BufferBytes));
     }
     else
     {
         buffer = new DSound.Buffer(FLD_SND + "firstaid.wav", snddev);
         buffer.SetCurrentPosition((int)(((float)tags / MAX_TAGS) * buffer.Caps.BufferBytes));
     }
     buffer.Play(0, DSound.BufferPlayFlags.Default);
 }
Beispiel #15
0
 private void HaltDXSound(Buffer buffer)
 {
     if (ProblemWithSound)
     {
         return;
     }
     try
     {
         buffer.Stop();
     }
     catch (Exception)
     {
         ProblemWithSound = true;
     }
 }
        public TgcDirectSound()
        {
            //Crear device de DirectSound
            dsDevice = new Device();
            dsDevice.SetCooperativeLevel(GuiController.Instance.MainForm, CooperativeLevel.Normal);

            //Crear Listener3D
            BufferDescription primaryBufferDesc = new BufferDescription();

            primaryBufferDesc.Control3D     = true;
            primaryBufferDesc.PrimaryBuffer = true;
            primaryBuffer          = new Microsoft.DirectX.DirectSound.Buffer(primaryBufferDesc, dsDevice);
            listener3d             = new Listener3D(primaryBuffer);
            listener3d.Position    = new Vector3(0f, 0f, 0f);
            listener3d.Orientation = new Listener3DOrientation(new Vector3(1, 0, 0), new Vector3(0, 1, 0));
        }
 public static void GetSounds(DataSet ds, BufferDescription bufferDesc, Device device)
 {
     ds.ReadXml("settings\\sound_data.xml");
     DataTable fileTable = ds.Tables["FileTable"];
     foreach (DataRow fileRow in fileTable.Rows)
     {
         fileRow["buffer"] = new Buffer((String)fileRow["filePath"], bufferDesc, device);
     }
     foreach (DataTable dt in ds.Tables)
     {
         if (dt.TableName == "FileTable") { continue; }
         foreach (DataRow dr in dt.Rows)
         {
             DataRow fileRow = fileTable.Select("fileId = '" + dr["fileId"] + "'")[0];
             dr["buffer"] = ((Buffer)fileRow["buffer"]).Clone(device);
         }
     }
 }
 public void PlaySound()
 {
     if ((buffer == null || !buffer.Status.Playing) && listBox.SelectedItem != null)
     {
         buffer = (Buffer)((DataRowView)listBox.SelectedItem).Row["buffer"];
         Buffer3D buffer3d = new Buffer3D(buffer);
         buffer3d.Mode = Mode3D.Normal;
         buffer3d.Position = location;
         buffer.Play(0, BufferPlayFlags.Default);
         if (listBox.SelectedIndex < listBox.Items.Count - 1)
         {
             listBox.SelectedIndex = listBox.SelectedIndex + 1;
         }
         else
         {
             listBox.SelectedIndex = 0;
         }
     }
 }
        public SoundListener3d(DirectSound.Device device)
        {
            // 3d setup
            m_descriptionListener = new DirectSound.BufferDescription();

            m_descriptionListener.ControlEffects = false;
            m_descriptionListener.Control3D      = true;
            m_descriptionListener.ControlVolume  = true;
            m_descriptionListener.PrimaryBuffer  = true;

            m_primary3d  = new DirectSound.Buffer(m_descriptionListener, device);
            m_listener3d = new DirectSound.Listener3D(m_primary3d);

            // default orientation
            DirectSound.Listener3DOrientation o = new DirectSound.Listener3DOrientation();
            o.Front = new Microsoft.DirectX.Vector3(0, 0, 1);   // facing forward
            o.Top   = new Microsoft.DirectX.Vector3(0, 1, 0);   // standing upright

            m_listener3d.Orientation = o;
        }
    public SoundBuffer(Microsoft.DirectX.DirectSound.Device soundDevice, string filename, Sounds thisSound, bool looping)
    {
        this.thisSound = thisSound;
        this.looping = looping;

        BufferDescription bufferDesc = new BufferDescription();
        bufferDesc.Flags = BufferDescriptionFlags.ControlVolume;

        try {
            buffer = new Microsoft.DirectX.DirectSound.Buffer(
                filename,
                bufferDesc,
                soundDevice);
        }
        catch (Exception e) {
            throw new Exception(
                String.Format("Error opening {0}; ",
                filename), e);
        }
    }
Beispiel #21
0
        private void PlayDXSound(Buffer buffer, int soundVolumeModifier, BufferPlayFlags flags)
        {
            if (ProblemWithSound)
            {
                return;
            }
            try
            {
                if (EngineConfig.SoundVolume == 0)
                {
                    return;
                }

                buffer.Play(0, flags);
                buffer.Volume = System.Math.Min(0, getBaseVolume() + soundVolumeModifier);
            }
            catch (Exception)
            {
                ProblemWithSound = true;
            }
        }
Beispiel #22
0
        public SoundBuffer(Microsoft.DirectX.DirectSound.Device soundDevice, string filename, Sounds thisSound, bool looping)
        {
            this.thisSound = thisSound;
            this.looping   = looping;

            BufferDescription bufferDesc = new BufferDescription();

            bufferDesc.Flags = BufferDescriptionFlags.ControlVolume;

            try {
                buffer = new Microsoft.DirectX.DirectSound.Buffer(
                    filename,
                    bufferDesc,
                    soundDevice);
            }
            catch (Exception e) {
                throw new Exception(
                          String.Format("Error opening {0}; ",
                                        filename), e);
            }
        }
Beispiel #23
0
 private void SelectEngineIdleSound(Model.Level.Planes.Plane p)
 {
     if (p.IsEngineFaulty)
     {
         currentEngineIdleSound = engineIdleFaultySound;
     }
     else
     {
         if (EngineConfig.CurrentPlayerPlaneType == PlaneType.P47)
         {
             currentEngineIdleSound = engineIdleSound;
         }
         else if (EngineConfig.CurrentPlayerPlaneType == PlaneType.F4U)
         {
             currentEngineIdleSound = engineIdleSound2;
         }
         else
         {
             currentEngineIdleSound = engineIdleSound3;
         }
     }
 }
Beispiel #24
0
        /// <summary>
        ///		Sets up an instance of DirectSound9Driver and sets ups
        ///		DirectSound so its render for audio playback.
        /// </summary>
        private void InitializeDevice()
        {
            // Setup the DirectSound device
            _dx9Device = new Device();
            if (GraphicsManager.RenderTarget as GraphicsCanvas != null)
            {
                _dx9Device.SetCooperativeLevel(((GraphicsCanvas)GraphicsManager.RenderTarget).RenderControl, CooperativeLevel.Priority);
            }

            // Create our 3D sound listener.
            BufferDescription bufferDescription = new BufferDescription();

            bufferDescription.PrimaryBuffer = true;
            bufferDescription.Control3D     = true;

            // Get the primary buffer
            Microsoft.DirectX.DirectSound.Buffer buffer = new Microsoft.DirectX.DirectSound.Buffer(bufferDescription, _dx9Device);

            // Attach the listener to the primary buffer
            _listener3D = new Listener3D(buffer);
            _listener3D.DistanceFactor = 0.03f;
            //_listener3D.DopplerFactor = 0.1f;
            //_listener3D.RolloffFactor = 0.1f;
        }
Beispiel #25
0
        private SoundManager()
        {
            try
            {
                int i = 1;
                while (File.Exists("music/music" + i.ToString() + ".ogg"))
                {
                    maxMusicTrackNo = MaxMusicTrackNo + 1;
                    i++;
                }
                maxMusicTrackNo = MaxMusicTrackNo - 1;

                random = new Random();


                gearUpSound       = new Audio("sounds/gear_up.wav");
                gearDownSound     = new Audio("sounds/gear_down.wav");
                startEngineSound  = new Audio("sounds/enginestart.wav");
                stopEngineSound   = new Audio("sounds/enginestop.wav");
                startEngineSound2 = new Audio("sounds/enginestart_f4u.wav");
                stopEngineSound2  = new Audio("sounds/enginestop_f4u.wav");



                failedEngineSound    = new Audio("sounds/startengine.wav");
                bunkerFireSound      = new Audio("sounds/cannon.wav");
                bunkerFireSound2     = new Audio("sounds/cannon2.wav");
                flakBunkerFireSound  = new Audio("sounds/flak.wav");
                flakBunkerFireSound2 = new Audio("sounds/flak2.wav");

                ricochetSound = new Audio("sounds/ricochet.wav");

                fortressFireSound = new Audio("sounds/fortress_cannon.wav");
                shipFireSound     = new Audio("sounds/ship_cannon.wav");


                explosionSound  = new Audio("sounds/explosion.wav");
                explosionSound3 = new Audio("sounds/explosion3.wav");

                explosionSound2 = new Audio("sounds/explosion2.wav");

                waterExplosionSound = new Audio("sounds/watersplash.wav");
                missileSound        = new Audio("sounds/missile.wav");
                smallMissileSound   = new Audio("sounds/small_missile.wav");

                torpedoSound = new Audio("sounds/torpedo.wav");

                catchPlaneSound = new Audio("sounds/landing.wav");
                bunkerRebuild   = new Audio("sounds/construction.wav");

                achievementFulFilled = new Audio("sounds/achievement.wav");

                startSubmergingSound = new Audio("sounds/ship_siren.wav");
                reloadSound          = new Audio("sounds/reload.wav");
                buzzerSound          = new Audio("sounds/buzzer.wav");
                bombSound            = new Audio("sounds/bombwhistle.wav");
                incorrectStart       = new Audio("sounds/incorrectstart.wav");
                fanfare = new Audio("sounds/fanfare.wav");

                currentEngineIdleSound = null;
                collisionSound         = new Audio("sounds/collision.wav");

                engineIdleSound = new Buffer("sounds/engineidle.wav",
                                             dsDevice);


                engineIdleSound2 = new Buffer("sounds/engineidle_f4u.wav",
                                              dsDevice);

                engineIdleSound3 = new Buffer("sounds/engineidle_b25.wav",
                                              dsDevice);

                engineIdleFaultySound = new Buffer("sounds/engineidlefaulty.wav",
                                                   dsDevice);


                /* enemyEngineSound = new Buffer("sounds/engineidle.wav",
                 *                             dsDevice);
                 *
                 * enemyEngineSound.Frequency =
                 *   enemyEngineSound.Format.SamplesPerSecond + C_NOMINAL_ENEMY_FREQ;*/


                gunFireBuffer = new Buffer("sounds/machinegun.wav",
                                           dsDevice);

                gunFireBuffer2 = new Buffer("sounds/machinegun_b25.wav",
                                            dsDevice);

                waterBubblesBuffer = new Buffer("sounds/waterbubbles.wav",
                                                dsDevice);


                oceanSound        = new Buffer("sounds/ocean.wav", dsDevice);
                oceanSound.Volume = -2400;

                torpedoRunSound = new Buffer("sounds/torpedo_run.wav", dsDevice);
                // torpedoRunSound.Volume = -2400;
            }
            catch (Exception ex)
            {
                LogManager.Singleton.LogMessage(LogMessageLevel.LML_CRITICAL, "DirectSound init error: " + ex.Message);
                ProblemWithSound = true;
            }
        }
        public override void SetRenderWindow(RenderWindow renderwindow, Camera camera)
        {
            base.SetRenderWindow(renderwindow, camera);

            // link the device to our current System.Windows.Form (since we need DirectX we're sure that we're in Windows)
            device.SetCooperativeLevel((System.Windows.Forms.Control)window.Handle, CooperativeLevel.Priority);

            // create a buffer for the listener
            BufferDescription desc = new BufferDescription();
            desc.Control3D = true;
            desc.PrimaryBuffer = true;
            Buffer lbuffer = new Buffer(desc, device);
            listener = new Listener3D(lbuffer);

            // let the log know that we're using DirectSound and it's set up
            LogManager.Instance.Write("DirectSound SoundSystem initialised");
        }
    Microsoft.DirectX.DirectSound.Buffer LoadFile(string filename)
    {
        Microsoft.DirectX.DirectSound.BufferDescription bufferDesc = new BufferDescription();
        bufferDesc.Flags = BufferDescriptionFlags.ControlVolume;

        Microsoft.DirectX.DirectSound.Buffer buffer;
        buffer = new Microsoft.DirectX.DirectSound.Buffer(filename, bufferDesc, soundDevice);

        return buffer;
    }
Beispiel #28
0
 private void LoopDXSound(Buffer buffer, int soundVolumeModifier)
 {
     PlayDXSound(buffer, soundVolumeModifier, BufferPlayFlags.Looping);
 }
Beispiel #29
0
        /// <summary>
        /// Funkcja inicjujaca dzialanie silnika dzwiekowego (laczy sie z karta
        /// dzwiekowa, tworzy niezbedne obiekty (tablica dzwiekow, listener,
        /// glowny bufor dzwiekowy, obiekt szukajacy sciezek do plikow)
        /// </summary>
        /// <param name="owner">Obiekt (Forms), w ktorym ma byc umieszczony 
        /// silnik dzwiekowy</param>
        /// <param name="distanceFactor">Czynnik odleglosci</param>
        /// <param name="roloffFactor">Czynnik roloff</param>
        /// <param name="volume">Glosnosc</param>
        public static void InitializeEngine(Control owner, int volume,
            float distanceFactor, float roloffFactor)
        {
            //karta dzwiekowa
            soundCard = new DS.Device();
            soundCard.SetCooperativeLevel(owner, CooperativeLevel.Normal);

            //lista dzwiekow
            soundList = new ArrayList();

            //listener
            primaryBufferDescription = new BufferDescription();
            primaryBufferDescription.ControlEffects = false;
            primaryBufferDescription.Control3D = true;
            primaryBufferDescription.PrimaryBuffer = true;
            primaryBufferDescription.ControlVolume = true;
            primaryBuffer = new DS.Buffer(primaryBufferDescription, soundCard);
            primaryBuffer.Volume = volume;

            listener = new Listener3D(primaryBuffer);
            listener.DistanceFactor = distanceFactor;
            listener.RolloffFactor = roloffFactor;

            //muzyka w tle

            //SourceNameFinder
            nameFinder = new SourceNameFinder();
        }
        /// <summary>
        ///   Read an audio file using mono format
        /// </summary>
        /// <param name = "pathToFile">File to read from. Should be a .wav file</param>
        /// <param name = "sampleRate">
        ///   Sample rate of the file. This proxy does not support down or up sampling.
        ///   Please convert the file to appropriate sample, and then use this method.
        /// </param>
        /// <param name = "secondsToRead">Seconds to read</param>
        /// <param name = "startAtSecond">Start at second</param>
        /// <returns>Audio samples</returns>
        public override float[] ReadMonoFromFile(string pathToFile, int sampleRate, int secondsToRead, int startAtSecond)
        {
            int totalSeconds = secondsToRead <= 0 ? int.MaxValue : secondsToRead + startAtSecond;
            if (alreadyDisposed)
            {
                throw new ObjectDisposedException("Object already disposed");
            }

            if (Path.GetExtension(pathToFile) != ".wav")
            {
                throw new ArgumentException(
                    "DirectSound can read only .wav files. Please transform your input file into appropriate type.");
            }

            Device device = new Device(new DevicesCollection()[0].DriverGuid);
            Buffer buffer = new Buffer(Path.GetFullPath(pathToFile), device);

            /*Default sound card is used as parent Device*/
            long fileSize = buffer.Caps.BufferBytes;
            int offset = 0;
            int bytesPerSample = buffer.Format.BitsPerSample / 8;
            const int OutputBufferSize = 5512 * 10 * 4;
            List<float[]> chunks = new List<float[]>();
            int size = 0;
            try
            {
                while ((float)size / sampleRate < totalSeconds)
                {
                    byte[] ar = (byte[])buffer.Read(offset, typeof(byte), LockFlag.EntireBuffer, OutputBufferSize);
                    offset += OutputBufferSize;
                    long readData = offset > fileSize ? fileSize - (offset - OutputBufferSize) : ar.Length;
                    float[] result = new float[readData / bytesPerSample];
                    for (int i = 0; i < result.Length; i++)
                    {
                        switch (bytesPerSample)
                        {
                            case 2:
                                result[i] = BitConverter.ToInt16(ar, i * bytesPerSample);
                                break;
                            case 4:
                                result[i] = BitConverter.ToInt32(ar, i * bytesPerSample);
                                break;
                        }
                    }

                    chunks.Add(result);
                    size += result.Length;
                    if (offset > fileSize)
                    {
                        break;
                    }
                }
            }
            finally
            {
                buffer.Stop();
                buffer.Dispose();
                device.Dispose();
            }

            if ((float)size / sampleRate < (secondsToRead + startAtSecond))
            {
                return null; /*not enough samples to return the requested data*/
            }

            int start = (int)((float)startAtSecond * sampleRate);
            int end = (secondsToRead <= 0) ? size : (int)((float)(startAtSecond + secondsToRead) * sampleRate);
            float[] data = new float[size];
            int index = 0;
            /*Concatenate*/
            foreach (float[] chunk in chunks)
            {
                Array.Copy(chunk, 0, data, index, chunk.Length);
                index += chunk.Length;
            }

            /*Select specific part of the song*/
            if (start != 0 || end != size)
            {
                float[] temp = new float[end - start];
                Array.Copy(data, start, temp, 0, end - start);
                data = temp;
            }

            return data;
        }
Beispiel #31
0
 private void LoopDXSound(Buffer buffer)
 {
     LoopDXSound(buffer, 0);
 }
        /// <summary>
        ///		Sets up an instance of DirectSound9Driver and sets ups 
        ///		DirectSound so its render for audio playback.
        /// </summary>
        private void InitializeDevice()
        {
            // Setup the DirectSound device
            _dx9Device = new Device();
            if (GraphicsManager.RenderTarget as GraphicsCanvas != null)
                _dx9Device.SetCooperativeLevel(((GraphicsCanvas)GraphicsManager.RenderTarget).RenderControl, CooperativeLevel.Priority);

            // Create our 3D sound listener.
            BufferDescription bufferDescription = new BufferDescription();
            bufferDescription.PrimaryBuffer = true;
            bufferDescription.Control3D = true;

            // Get the primary buffer
            Microsoft.DirectX.DirectSound.Buffer buffer = new Microsoft.DirectX.DirectSound.Buffer(bufferDescription, _dx9Device);

            // Attach the listener to the primary buffer
            _listener3D = new Listener3D(buffer);
            _listener3D.DistanceFactor = 0.03f;
            //_listener3D.DopplerFactor = 0.1f;
            //_listener3D.RolloffFactor = 0.1f;
        }
Beispiel #33
0
    public Play3DSound()
    {
        try
        {
            // Load the icon from our resources
            System.Resources.ResourceManager resources = new System.Resources.ResourceManager(this.GetType());
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
        }
        catch
        {
            // It's no big deal if we can't load our icons, but try to load the embedded one
            try { this.Icon = new System.Drawing.Icon(this.GetType(), "directx.ico"); }
            catch {}
        }
        //
        // Required for Windows Form Designer support
        //

        InitializeComponent();

        BufferDescription description = new BufferDescription();
        WaveFormat        fmt         = new WaveFormat();

        description.PrimaryBuffer = true;
        description.Control3D     = true;
        Buffer buff = null;

        fmt.FormatTag             = WaveFormatTag.Pcm;
        fmt.Channels              = 2;
        fmt.SamplesPerSecond      = 22050;
        fmt.BitsPerSample         = 16;
        fmt.BlockAlign            = (short)(fmt.BitsPerSample / 8 * fmt.Channels);
        fmt.AverageBytesPerSecond = fmt.SamplesPerSecond * fmt.BlockAlign;

        try
        {
            applicationDevice = new Device();
            applicationDevice.SetCooperativeLevel(this, CooperativeLevel.Priority);
        }
        catch
        {
            MessageBox.Show("Unable to create sound device. Sample will now exit.");
            this.Close();
            throw;
        }

        // Get the primary buffer and set the format.
        buff        = new Buffer(description, applicationDevice);
        buff.Format = fmt;

        applicationListener = new Listener3D(buff);
        listenerParameters  = applicationListener.AllParameters;

        labelFilename.Text = String.Empty;
        labelStatus.Text   = "No file loaded.";

        string path = Utility.FindMediaFile("grid.jpg");

        pictureboxRenderWindow.BackgroundImage = Image.FromFile(path);
        GridWidth  = pictureboxRenderWindow.Width;
        GridHeight = pictureboxRenderWindow.Height;

        trackbarDopplerSlider.Maximum = ConvertLogScaleToLinearSliderPos(DSoundHelper.MaxDopplerFactor);
        trackbarDopplerSlider.Minimum = ConvertLogScaleToLinearSliderPos(DSoundHelper.MinDopplerFactor);

        trackbarRolloffSlider.Maximum = ConvertLogScaleToLinearSliderPos(DSoundHelper.MaxRolloffFactor);
        trackbarRolloffSlider.Minimum = ConvertLogScaleToLinearSliderPos(DSoundHelper.MinRolloffFactor);

        trackbarMindistanceSlider.Maximum = 40;
        trackbarMindistanceSlider.Minimum = 1;

        trackbarMaxdistanceSlider.Maximum = 40;
        trackbarMaxdistanceSlider.Minimum = 1;

        trackbarVerticalSlider.Maximum = 100;
        trackbarVerticalSlider.Minimum = -100;
        trackbarVerticalSlider.Value   = 100;

        trackbarHorizontalSlider.Maximum = 100;
        trackbarHorizontalSlider.Minimum = -100;
        trackbarHorizontalSlider.Value   = 100;

        SetSlidersPos(0, 0, maxOrbitRadius, maxOrbitRadius * 20.0f);
        SliderChanged();
    }
 public SoundData(Vector3 loc, ListBox box, Buffer buf)
 {
     location = loc;
     listBox = box;
     buffer = buf;
 }
Beispiel #35
0
 void PlaySound(string snd)
 {
     DSound.Buffer buffer = new DSound.Buffer(FLD_SND + snd, snddev);
     buffer.Play(0, DSound.BufferPlayFlags.Default);
 }