Example #1
0
 public void EmitDah()
 {
     setBufferAndWave(dahunit);
     buffer.Write(0, GenerateOneUnitSound(dahunit), LockFlag.EntireBuffer);
     buffer.Volume = (int)Volume.Max;
     buffer.Play(0, BufferPlayFlags.Default);
 }
Example #2
0
 public void DifferentStartPlaying()
 {
     if (_enum10 == AudioStatus.IsCurrentlyPlayingAudio)
     {
         method_0();
         return;
     }
     if (_enum10 == AudioStatus.ShouldStopAudio)
     {
         method_9();
         method_2(5);
         _long0 = 0L;
         _int2  = 0;
         _secondaryBuffer0.SetCurrentPosition(0);
         method_4();
         for (var i = 0; i < 5; i++)
         {
             method_7();
         }
         _secondaryBuffer0.SetCurrentPosition(0);
         _secondaryBuffer0.Volume = 0;
         _secondaryBuffer0.Play(0, BufferPlayFlags.Looping);
         _enum10 = AudioStatus.ShouldStartAudio;
     }
 }
Example #3
0
        private void btn_play_Click(object sender, EventArgs e)//press play button;
        {
            // Set initial amplitude and frequency
            try
            {
                bool   Is_input_OK = true;
                double frequency_L = 1000;
                double frequency_R = 1000;
                if (syncLR == false)
                {
                    frequency_L = Convert.ToDouble(tB_L.Text);
                    frequency_R = Convert.ToDouble(tB_R.Text);
                }
                else
                {
                    frequency_R = frequency_L;
                    tB_R.Text   = tB_L.Text;
                }
                if (frequency_L > 20000 || frequency_L < 20)
                {
                    Is_input_OK = false;
                }
                if (frequency_R > 20000 || frequency_R < 20)
                {
                    Is_input_OK = false;
                }
                if (!Is_input_OK)
                {
                    MessageBox.Show("输入频率范围在:20-20000");
                    return;
                }
                double amplitude = short.MaxValue;
                double two_pi    = 2 * Math.PI;
                // Iterate through time
                for (int i = 0; i < buffer.Length / 2; i++)
                {
                    // Add to sine
                    buffer[2 * i]     = (short)(amplitude * Math.Sin(i * two_pi * frequency_L / waveFormat.SamplesPerSecond));
                    buffer[2 * i + 1] = (short)(amplitude * Math.Sin(i * two_pi * frequency_R / waveFormat.SamplesPerSecond));
                }

                bufferSound.Volume = (vol == 0)?-10000:-600 * (10 - vol);//(int)Volume.Max;
                bufferSound.Write(0, buffer, LockFlag.None);
                bufferSound.Play(0, BufferPlayFlags.Looping);

                isSync.Enabled = false;//disable sync checkbox;
            }
            catch
            {
                MessageBox.Show("输入错误!");
            }

            if (bufferSound.Status.Playing)
            {
                btn_play.Enabled = false; Sweep.Enabled = false; btn_stop.Enabled = true;
            }
        }
 /// <summary>
 ///		Starts playing this sample buffer.
 /// </summary>
 void ISampleBuffer.Play()
 {
     _buffer.Play(0, (_flags & SoundFlags.Streamed) != 0 ? (_streamFinishing == true ? 0 : BufferPlayFlags.Looping) : (_isLooping ? BufferPlayFlags.Looping : 0));
     _isPlaying = true;
     _started   = true;
     if (_streamingThread != null && _streamingThread.IsAlive == false)
     {
         _streamingThread.Start();
     }
 }
Example #5
0
 public bool Resume()
 {
     // returns if resume action was successful
     if (buffer != null)
     {
         buffer.SetCurrentPosition(m_lastPlayingPosition);
         buffer.Play(0, BufferPlayFlags.Looping);
         return(true);
     }
     return(false);
 }
Example #6
0
        public void Resume()
        {
            if (!_halted)
            {
                return;
            }

            _halted = false;
            _soundBuffer.Play(0, BufferPlayFlags.Looping);

            Monitor.Pulse(_thread);
            Monitor.Exit(_thread);
        }
Example #7
0
        /*in BufferCaps
         * public int PlayCpuOverhead [  get]
         *  Member of Microsoft.DirectX.DirectSound.BufferCaps
         *
         * Summary:
         * The processing overhead as a percentage of main processor cycles needed to mix this sound buffer. For hardware buffers, this member will be zero because the mixing is performed by the sound device. For software buffers, this member depends on the buffer format and the speed of the system processor.
         */
        private void button4_Click(object sender, System.EventArgs e)
        {
            //Create and setup the sound device.
            Device dev = new Device();

            dev.SetCooperativeLevel(this, CooperativeLevel.Normal);

            //Create and setup the buffer description.
            BufferDescription buffer_desc = new BufferDescription();

            buffer_desc.ControlEffects = true;  //this has to be true to use effects.
            buffer_desc.GlobalFocus    = true;  //play sound even if application loses focus.

            //Create and setup the buffer for playing the sound.
            SecondaryBuffer buffer = new SecondaryBuffer(
                @"C:\WINDOWS\Media\ding.wav",
                buffer_desc,
                dev);

            //Create an array of effects descriptions,
            //set the effect objects to echo and chorus and
            //set it in the buffer.
            EffectDescription[] effects = new EffectDescription[2];
            effects[0].GuidEffectClass = DSoundHelper.StandardEchoGuid;
            effects[1].GuidEffectClass = DSoundHelper.StandardChorusGuid;
            buffer.SetEffects(effects);

            //Play Buffer.
            buffer.Play(0, BufferPlayFlags.Default);
        }
Example #8
0
        private void Play(string filename)
        {
            StreamReader reader = new StreamReader(filename);

            WaveFormat format = new WaveFormat();

            format.AverageBytesPerSecond = bitspersample / 8 * samplerate;
            format.BitsPerSample         = bitspersample;
            format.BlockAlign            = bitspersample / 8;
            format.Channels         = 1;
            format.FormatTag        = WaveFormatTag.Pcm;
            format.SamplesPerSecond = samplerate;

            BufferDescription desc = new BufferDescription(format);

            desc.BufferBytes   = (int)reader.BaseStream.Length;
            desc.ControlVolume = true;
            desc.GlobalFocus   = true;

            buffer = new SecondaryBuffer(desc, dev);
            //buffer = new SecondaryBuffer(filename, dev);
            buffer.Write(0, reader.BaseStream, (int)reader.BaseStream.Length, LockFlag.None);

            reader.Close();

            //m_BufferBytes = buffer.Caps.BufferBytes;


            buffer.Play(0, BufferPlayFlags.Default);
        }
Example #9
0
        /*
         * Receive audio data coming on port 1550 and feed it to the speakers to be played.
         */
        private void UDP_Receive()
        {
            try {
                bStop = false;
                IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);

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

                    string c_ip = remoteEP.Address.ToString();


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

                    //Decompress data using the proper vocoder.
                    ALawDecoder.ALawDecode(byteData, out byteDecodedData);

                    //Play the data received to the user.
                    playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);
                    playbackBuffer.Write(0, byteDecodedData, LockFlag.None);
                    playbackBuffer.Play(0, BufferPlayFlags.Default);
                }
            } catch (Exception ex) {
                //MessageBox.Show(ex.Message, "VoiceChat-Receive ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            } finally {
                nUdpClientFlag += 1;
            }
        }
Example #10
0
File: main.cs Project: sjk7/DX90SDK
 private void btnPlay_Click(object sender, System.EventArgs e)
 {
     if (null != ApplicationBuffer)
     {
         ApplicationBuffer.Play(0, (cbLoopCheck.Checked ? BufferPlayFlags.Looping : BufferPlayFlags.Default));
     }
 }
Example #11
0
        public void StartPlaying(MemoryStream buffer)
        {
            if (buffer == null)
            {
                return;
            }
            buffer.Position = 0;

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

            // buffer description
            BufferDescription bufferDescription = new BufferDescription(mWaveFormat);

            bufferDescription.DeferLocation = true;
            bufferDescription.BufferBytes   = Convert.ToInt32(buffer.Length);
            mSecondaryBuffer = new SecondaryBuffer(bufferDescription, mDevice);

            //load audio samples to secondary buffer
            mSecondaryBuffer.Write(0, buffer, Convert.ToInt32(buffer.Length), LockFlag.EntireBuffer);

            //play audio buffer
            mSecondaryBuffer.Play(0, BufferPlayFlags.Default);
        }
Example #12
0
		/// <summary>
		/// Plays a sound.
		/// </summary>
		/// <param name="id">The ChannelId identifing the SoundManger playing the sound and the channel number.</param>
		/// <param name="buffer">A SecondaryBuffer containing the sound to be playing.</param>
		/// <param name="frequencymultiplier">The multiplier applied the sound to change its pitch. 1.0f for no change.</param>
		/// <param name="looping">Whether the sound should loop automatically until stopped.</param>
		/// <param name="volume">The volume level of the sound.</param>
		public void Play(ChannelId id, SecondaryBuffer buffer, Single frequencymultiplier, Boolean looping, Int32 volume)
		{
			if (buffer == null) throw new ArgumentNullException("buffer");
			if (volume > (Int32)Volume.Max || volume < (Int32)Volume.Min) throw new ArgumentOutOfRangeException("volume");

			Stop();

			m_usingid = id;
			m_buffer = buffer;

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

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

			m_playflags = flags;

			try
			{
				m_buffer.Play(0, flags);
			}
			catch { }
		}
        public void PlaySound()
        {
            try
            {
                BufferPlayFlags flags;
                if (looping)
                {
                    flags = BufferPlayFlags.Looping;
                }
                else
                {
                    flags = BufferPlayFlags.Default;
                }

                if (RestoreBuffer())
                {
                    LoadSoundFile();
                    soundBuffer.SetCurrentPosition(0);
                }
                soundBuffer.Play(0, flags);
            }
            catch (Exception e)
            {
                GameEngine.Console.AddLine("Exception on playing " + m_FileName);
                GameEngine.Console.AddLine(e.Message);
            }
        }
Example #14
0
        public void playWav()
        {
            if (wavFile.Contains(".mp3"))
            {
                wplayer.URL = wavFile;
                wplayer.controls.play();
            }
            else
            {
                switch (playerType)
                {
                case PlayerType.ACTIVEX:
                {
                    wavPlayer.SoundLocation = wavFile;
                    wavPlayer.Play();
                    break;
                }

                case PlayerType.DIRECTSOUND:
                {
                    sound = new SecondaryBuffer(wavFile, buffDesc, soundDevice);
                    sound.Play(0, BufferPlayFlags.Default);
                    break;
                }
                }
            }
        }
Example #15
0
        public override void play(string file, bool isName)
        {
            if (isName)
            {
                path = platformSpec.main.appPath + "\\sounds\\" + path;
            }

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

                    if (e != System.IO.FileNotFoundException)
                    {
                        working = false;
                    }
                }
            }
        }
Example #16
0
        public void PlayBgm(int ID, bool IsLoop = true)
        {
            if (ID == BGMPlayID)
            {
                return;
            }
            if (IsLoop)
            {
                BGMPlayID = ID;
            }
            else
            {
                BGMPlayID = -1;
            }

            buffDes               = new BufferDescription();
            buffDes.GlobalFocus   = true;
            buffDes.ControlVolume = true;

            if (secBufferBGM != null)
            {
                secBufferBGM.Stop();
                secBufferBGM.Dispose();
                secBufferBGM = null;
            }
            secBufferBGM = new SecondaryBuffer(bgm_path + bgm_str[ID], buffDes, ds);
            ChangeVolume();
            secBufferBGM.Play(0, IsLoop ? BufferPlayFlags.Looping : BufferPlayFlags.Default);
        }
Example #17
0
        private void playOrStopButton__Click(object sender, EventArgs e)
        {
            if (secondaryBuffer_ == null)
            {
                device_.SetCooperativeLevel(this, CooperativeLevel.Normal);

                bufferDescription_ = new BufferDescription()
                {
                    GlobalFocus           = true,
                    ControlVolume         = true,
                    ControlPositionNotify = true,
                };

                secondaryBuffer_ = new SecondaryBuffer(filePathTextBox_.Text, device_);
                secondaryBuffer_.Play(0, BufferPlayFlags.Default);

                playOrStopButton_.Text = "Stop";
                stopButton_.Enabled    = true;
            }
            else if (secondaryBuffer_.Status.Playing)
            {
                secondaryBuffer_.Stop();
                playOrStopButton_.Text = "Play";
            }
        }
Example #18
0
        /*
         * Receive audio data coming on port 1550 and feed it to the speakers to be played.
         */
        private void Receive()
        {
            try
            {
                bStop = false;
                IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);

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

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

                    //Decompress data using the proper vocoder. And decrypt
                    var decryptedData = AES_Crypto.Decrypt(byteData, CallCurrentPass, CallCurrentSalt);
                    ALawDecoder.ALawDecode(decryptedData, out byteDecodedData);

                    //Play the data received to the user.
                    playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);
                    playbackBuffer.Write(0, byteDecodedData, LockFlag.None);
                    playbackBuffer.Play(0, BufferPlayFlags.Default);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "VoiceChat-Receive ()", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
            }
            finally
            {
                nUdpClientFlag += 1;
            }
        }
Example #19
0
        /*
         * Receive audio data coming on port 1550 and feed it to the speakers to be played.
         */
        private void Receive()
        {
            try
            {
                udpAudioReceiving = new UdpClient(1550);
                IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);

                audioReceive = true;
                while (audioReceive)
                {
                    //Receive data.
                    byte[] byteData = udpAudioReceiving.Receive(ref remoteEP);

                    //Play the data received to the user.
                    playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);
                    playbackBuffer.Write(0, byteData, LockFlag.None);
                    playbackBuffer.Play(0, BufferPlayFlags.Default);
                }
            }
            catch (Exception ex)
            {
                Receive();
                //MessageBox.Show(ex.Message, "StudentSide:VideoWindow:Receive()", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //return;
            }
        }
Example #20
0
        byte[] addbuffer;                 // contains 30 waveforms


        private void btnGo_Click(object sender, EventArgs e)
        {
            // Button is either "stop" or "go"
            if (!timer.Enabled)
            {
                timer_Tick(null, null); //fill buffer initially
                bufferstream.Play(0, BufferPlayFlags.Looping);
                timer.Enabled              = true;
                timerDisplay.Enabled       = true;
                this.MainMenuStrip.Enabled = false;

                if (this.deviceInput != null)
                {
                    timerPoll.Enabled = true; // if game pad connected, poll the input device !
                }
                btnGo.Text = "Stop";
            }
            else
            {
                bufferstream.Stop();
                timer.Enabled              = false;
                timerDisplay.Enabled       = false;
                timerPoll.Enabled          = false;
                this.MainMenuStrip.Enabled = true;
                btnGo.Text = "Start";
            }
        }
Example #21
0
        private void win()//判断赢
        {
            if (flagwin == eng.Length)
            {
                resultlabel.Visible  = true;
                resultlabel.Text     = "YOU WIN!";
                panel1.Enabled       = false;
                chineselabel.Visible = true;
                score          += 10;
                scorelabel.Text = score.ToString();
                timer1.Stop();
                startbutton.Visible = true;
                startbutton.Text    = "Continue";
                unenbledtool();
                SecondaryBuffer secBuffer1;                                 //缓冲区对象
                Device          secDev1;                                    //设备对象
                secDev1 = new Device();
                secDev1.SetCooperativeLevel(this, CooperativeLevel.Normal); //设置设备协作级别
                secBuffer1 = new SecondaryBuffer(@"yes.wav", secDev1);      //创建辅助缓冲区
                secBuffer1.Play(0, BufferPlayFlags.Default);                //设置缓冲区为默认播放

                if (score > Convert.ToInt32(File.ReadAllText(@"score.txt")))
                {
                    timer2.Start();
                }
            }
        }
 private void Receive()
 {
     try
     {
         playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);
         while (flagSrarting)
         {
             byte[] array  = udpRecive.Receive(ref recive_Com);
             byte[] array2 = new byte[checked (array.Length + 1)];
             array2 = array;
             playbackBuffer.Dispose();
             playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);
             playbackBuffer.Write(0, array2, LockFlag.None);
             playbackBuffer.Play(0, BufferPlayFlags.Default);
         }
         playbackBuffer.Dispose();
         udpRecive.Close();
     }
     catch (Exception ex)
     {
         ProjectData.SetProjectError(ex);
         Exception ex2 = ex;
         ProjectData.ClearProjectError();
     }
     finally
     {
     }
 }
        /// <summary>
        /// 语音播放
        /// </summary>
        public override void ReadSound(string file)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(m_strDeviceDescription) ||
                    string.IsNullOrWhiteSpace(file) ||
                    !m_hashDevices.ContainsKey(m_strDeviceDescription))
                {
                    return;
                }

                if (File.Exists(file) == false)
                {
                    return;
                }

                if (null != m_buf)
                {
                    m_buf.Stop();
                    m_buf.Dispose();
                    m_buf = null;
                }
                using (BufferDescription temp = new BufferDescription())
                {
                    temp.Flags = BufferDescriptionFlags.GlobalFocus;
                    m_buf      = new SecondaryBuffer(file, temp, (Device)m_hashDevices[m_strDeviceDescription]);
                    m_buf.Play(0, BufferPlayFlags.Default);
                }
            }
            catch (Exception ex)
            {
                CLOGException.Trace("SoundManagementLib.CSoundDirectX.ReadSound 异常", CBaseMethods.MyBase.GetExceptionInfo(ex));
            }
        }
Example #24
0
        /*
         * Receive audio data coming on port 1550 and feed it to the speakers to be played.
         */
        private void Receive()
        {
            try
            {
                bStop = false;
                IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);

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

                    //Play the data received to the user.
                    playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);
                    playbackBuffer.Write(0, byteData, LockFlag.None);
                    playbackBuffer.Play(0, BufferPlayFlags.Default);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "VoiceChat-Receive ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                nUdpClientFlag += 1;
            }
        }
Example #25
0
        /// <summary>
        /// Plays a sound.
        /// </summary>
        /// <param name="id">The ChannelId identifing the SoundManger playing the sound and the channel number.</param>
        /// <param name="buffer">A SecondaryBuffer containing the sound to be playing.</param>
        /// <param name="frequencymultiplier">The multiplier applied the sound to change its pitch. 1.0f for no change.</param>
        /// <param name="looping">Whether the sound should loop automatically until stopped.</param>
        /// <param name="volume">The volume level of the sound.</param>
        public void Play(ChannelId id, SecondaryBuffer buffer, Single frequencymultiplier, Boolean looping, Int32 volume)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (volume > (Int32)Volume.Max || volume < (Int32)Volume.Min)
            {
                throw new ArgumentOutOfRangeException("volume");
            }

            Stop();

            m_usingid = id;
            m_buffer  = buffer;

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

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

            m_playflags = flags;

            try
            {
                m_buffer.Play(0, flags);
            }
            catch { }
        }
Example #26
0
 // --------------------------------------------------------------------
 // Initialize the DirectSound subsystem
 // --------------------------------------------------------------------
 public void InitializeSound()
 {
     // set up a device
     _sound = new Device();
     _sound.SetCooperativeLevel(this, CooperativeLevel.Normal);
     _wave = new SecondaryBuffer("..\\..\\air_whoosh.wav", _sound);
     _wave.Play(0, BufferPlayFlags.Looping);
 }
Example #27
0
 public void Play(bool loop)
 {
     _buffer.Play(0, loop ? BufferPlayFlags.Looping : BufferPlayFlags.Default);
     if (_is3d && loop && MuteAtMaximumDistance)
     {
         Engine.Audio.Register3dSound(this);
     }
 }
 public void Resume()
 {
     if (_buffer != null)
     {
         _buffer.SetCurrentPosition(_currentPosition);
         _buffer.Play(0, BufferPlayFlags.Default);
     }
 }
Example #29
0
        private void DirectSound_Button_Click(object sender, EventArgs e)
        {
            var device = new Device();

            device.SetCooperativeLevel(this, CooperativeLevel.Priority);
            SecondaryBuffer wavSound = new SecondaryBuffer(@"C:\Users\oszust\source\repos\UP1\UP1\example.wav", device);

            wavSound.Play(0, BufferPlayFlags.Default);
        }
Example #30
0
        public static void MonsterDie_BGM()
        {
            //怪物死亡
            SecondaryBuffer secBuffer;

            secBuffer        = new SecondaryBuffer(Properties.Resources.僵尸死亡音效, SoundPlayer.secDev); //创建辅助缓冲区
            secBuffer.Volume = 0;
            secBuffer.Play(0, BufferPlayFlags.Default);                                              //设置缓冲区为默认播放
        }
Example #31
0
 public void play()
 {
     if (sound == null)
     {
         return;
     }
     sound.Play(0, BufferPlayFlags.Looping);
     Parent.PlayerUpdate = 1;
 }
Example #32
0
        /// <summary>
        /// plays a sound in loop.
        /// </summary>
        /// <param name="e">Sound to play in loop</param>
        /// <returns>loopID assigned to the loop.</returns>
        public static int playInLoop(Sound e)
        {
            MemoryStream ms = e.getStream();
            //Can cause out of memory exception.
            SecondaryBuffer buffer = new SecondaryBuffer(ms, device);
            buffer.Play(0, BufferPlayFlags.Looping);

            loops.Add(loopID, buffer);
            return loopID++;
        }
Example #33
0
        public void PlaySound(Stream EmbeddedSoundStream, bool Loop)
        {
            try
            {
                _soundBuffer = new SecondaryBuffer(EmbeddedSoundStream, _bufferDesc, _soundDevice);
                _buffer3D = new Buffer3D(_soundBuffer);
                if (Loop)
                {
                    _soundBuffer.Play(0, BufferPlayFlags.Looping);
                }
                else
                {

                    _soundBuffer.Play(0, BufferPlayFlags.Default);
                }
            }
            catch (Exception expPlay)
            {
                Console.WriteLine(expPlay.Message);
            }
        }
Example #34
0
        public void PlaySound(string FullResourceName, bool Loop)
        {
            try
            {
                Stream strmTemp = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(FullResourceName);
                _soundBuffer = new SecondaryBuffer(strmTemp, _bufferDesc, _soundDevice);
                _buffer3D = new Buffer3D(_soundBuffer);
                if (Loop)
                {
                    _soundBuffer.Play(0, BufferPlayFlags.Looping);
                }
                else
                {

                    _soundBuffer.Play(0, BufferPlayFlags.Default);
                }
            }
            catch (Exception expPlay)
            {
                Console.WriteLine(expPlay.Message);
            }
        }
Example #35
0
		private void button1_Click(object sender, EventArgs e)
		{
			sound = new SecondaryBuffer(currFile, d, dSound);
			len = sound.Caps.BufferBytes;
			string info = "Sound Info:\n";
			info += "Sample Freq: " + sound.Format.SamplesPerSecond.ToString() + "\n";
			info += "Bit/Sample: " + sound.Format.BitsPerSample.ToString() + "\n";
			info += "Channels: " + sound.Format.Channels.ToString() + "\n";
			info += "Tot Bytes: " + sound.Caps.BufferBytes.ToString() + "\n";
			info += "Bytes/sec: " + sound.Format.AverageBytesPerSecond.ToString() + "\n";
			info += "Duration: " + ((int)(len / sound.Format.AverageBytesPerSecond)).ToString() + " sec\n";
			label1.Text = info;

			sound.Play(0, BufferPlayFlags.Default);
		}
Example #36
0
        public void TestMethod1()
        {
            // Set up wave format
            WaveFormat waveFormat = new WaveFormat();
            waveFormat.FormatTag = WaveFormatTag.Pcm;
            waveFormat.Channels = 1;
            waveFormat.BitsPerSample = 16;
            waveFormat.SamplesPerSecond = 44100;
            waveFormat.BlockAlign = (short) ( waveFormat.Channels * waveFormat.BitsPerSample / 8 );
            waveFormat.AverageBytesPerSecond = waveFormat.BlockAlign * waveFormat.SamplesPerSecond;

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

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

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

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

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

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

            SecondaryBuffer bufferSound = new SecondaryBuffer( bufferDesc, d );
            bufferSound.Volume = (int) Volume.Max;
            bufferSound.Write( 0, buffer, LockFlag.None );
            bufferSound.Play( 0, BufferPlayFlags.Default );
            System.Threading.Thread.Sleep( 10000 );
        }
Example #37
0
        public static void PlayForever()
        {
            ThreadStart play = () =>
                {
                    Thread.CurrentThread.IsBackground = true;
                    Thread.CurrentThread.Priority = ThreadPriority.Lowest;
                    DirectoryInfo di = HelpfulStuff.BaseDirectory;

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

                        BufferDescription description = new BufferDescription();
                        description.ControlEffects = false;
                        description.ControlVolume = true;
                        while (true)
                        {
                            foreach (FileInfo file in di.GetFiles("*.wav"))
                                try
                                {
                                    SecondaryBuffer shotsound = new SecondaryBuffer(file.FullName, description, sounddevice);
                                    try
                                    {
                                        shotsound.Play(0, BufferPlayFlags.Default);
                                        while (shotsound.Status.Playing)
                                        {
                                            shotsound.Volume = Mute ? -10000 : 0;
                                            Thread.Sleep(100);
                                        }
                                        Thread.Sleep(2000);
                                    }
                                    catch { shotsound.Dispose(); }
                                }
                                catch { }
                        }
                    }
                    catch
                    {
                        MessageBox.Show("DirectSound initialization failed. You won`t have music...");
                        return;
                    }
                };
            new Thread(play).Start();
        }
Example #38
0
        public void Play()
        {
            if (_mStream == null) return;

            _mStream.Seek(0, SeekOrigin.Begin);

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

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

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

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

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

        }
Example #39
0
        public void playbytes(Byte[] soundbytes, int bitsPerSample, int sampleRate)
        {
            int bytesPerSample;
            if (bitsPerSample == 8) bytesPerSample = 1;
            else if (bitsPerSample == 16) bytesPerSample = 2;
            else throw new NotSupportedException("Supports 8bit or 16bit");

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

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

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

            SecondaryBuffer currentBuffer = new SecondaryBuffer(desc, deviceSound);
            currentBuffer.Write(0, soundbytes, LockFlag.EntireBuffer);
            currentBuffer.Play(0, BufferPlayFlags.Default);
        }
Example #40
0
		public override void play( string file, bool isName )
		{
			if ( isName )
				path = platformSpec.main.appPath + "\\sounds\\" + path;

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

					if ( e != System.IO.FileNotFoundException )
						working = false;
				}
		}
        private void startPlaybackDirectSound()
        {
            WaveFormat format = new WaveFormat();
            format.BitsPerSample = 8;
            format.Channels = 1;
            format.BlockAlign = 1;

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

            // buffer description
            BufferDescription desc = new BufferDescription(format);
            desc.DeferLocation = true;
            desc.ControlVolume = true;
            double bytesEstimate = getSoundDuration() * ((double)format.AverageBytesPerSecond);
            desc.BufferBytes = Convert.ToInt32(bytesEstimate);

            // create the buffer
            //Device ApplicationDevice = new Device();

            activeSoundBuffer = new SecondaryBuffer(desc, soundDevice);
            setVolume();

            //generate ramdom data (white noise)
            byte[] rawsamples = new byte[desc.BufferBytes];
            Random rnd = new System.Random();

            for (int i = 0; i < desc.BufferBytes; i++)
            {
                //-----------------------------------------------
                //Completely random
                //add a new audio sample to array
                rawsamples[i] = (byte)rnd.Next(255);
                //-----------------------------------------------

            }

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

            activeSoundBuffer.Play(0, BufferPlayFlags.Looping);
        }
Example #42
0
File: Main.cs Project: ptaa32/ARDOP
 public bool PlaySoundStream()
 {
     bool functionReturnValue = false;
     //   Plays the .wav stream with the selected Playback device
     //   Returns True if no errors False otherwise...
     System.DateTime dttStartPlay = default(System.DateTime);
     int intTrace = 0;
     Status stcStatus = null;
     if (!blnCodecStarted)
         return false;
     if ((memWaveStream == null))
     {
         Logs.Exception("[PlaySoundFile] memWaveStream is nothing");
         return false;
     }
     else if (objPlayback != null && objPlayback.Status.Playing)
     {
         Logs.Exception("[PlaySoundFile] objPlayback is Playing, Call AbortWaveStream");
         AbortSoundStream();
     }
     intTrace = 1;
     try
     {
         intTrace = 2;
         devSelectedPlaybackDevice.SetCooperativeLevel(this.Handle, CooperativeLevel.Priority);
         //dttStartWaveStreamPlay = Now
         KeyPTT(true);
         // Activate PTT before starting sound play
         Microsoft.DirectX.DirectSound.BufferDescription bufPlaybackFlags = new Microsoft.DirectX.DirectSound.BufferDescription();
         // The following flags required to allow playing when not in focus and
         // to allow adjusting the volume...
         bufPlaybackFlags.Flags = (BufferDescriptionFlags)BufferDescriptionFlags.GlobalFocus + BufferDescriptionFlags.ControlVolume;
         intTrace = 3;
         memWaveStream.Seek(0, SeekOrigin.Begin);
         // reset the pointer to the origin
         intTrace = 4;
         objPlayback = new SecondaryBuffer(memWaveStream, bufPlaybackFlags, devSelectedPlaybackDevice);
         objPlayback.Volume = Math.Min(-5000 + 50 * MCB.DriveLevel, 0);
         // -5000=off, 0=full volume
         intTrace = 5;
         objPlayback.Play(0, BufferPlayFlags.Default);
         //objWMProtocol.SetCaptureState(CaptureState.Transmitting)
         dttTestStart = Now;
         dttStartPlay = Now;
         intTrace = 6;
         // wait up to 300 ms for start of playback.
         while (Now.Subtract(dttStartPlay).TotalMilliseconds < 300 & !objPlayback.Status.Playing)
         {
             Thread.Sleep(10);
         }
         intTrace = 7;
         if (objPlayback.Status.Playing)
         {
             intTrace = 8;
             if (MCB.DebugLog)
                 Logs.WriteDebug("[PlaySoundStream] Stream: " + strLastWavStream);
             stcStatus.ControlName = "lblXmtFrame";
             stcStatus.Text = strLastWavStream;
             stcStatus.BackColor = Color.LightSalmon;
             queTNCStatus.Enqueue(stcStatus);
             stcStatus.ControlName = "lblRcvFrame";
             stcStatus.BackColor = SystemColors.Control;
             stcStatus.Text = "";
             queTNCStatus.Enqueue(stcStatus);
             functionReturnValue = true;
         }
         else
         {
             intTrace = 9;
             KeyPTT(false);
             functionReturnValue = false;
             //objWMProtocol.SetCaptureState(CaptureState.SearchForLeader)
             Logs.WriteDebug("[PlaySoundStream] Failure to start objPlayback");
             Logs.Exception("[PlaySoundStream] Failure to start objPlayback");
         }
     }
     catch (Exception e)
     {
         Logs.Exception("[PlaySoundStream] Kill PTT on exception: " + e.ToString + "  intTrace=" + intTrace.ToString);
         KeyPTT(false);
         functionReturnValue = false;
         //objWMProtocol.SetCaptureState(CaptureState.SearchForLeader)
     }
     return functionReturnValue;
 }
Example #43
0
        private int intNotifySize = 5000;  // 設置通知大小

        #region 以自節數組中獲取音頻數據,並進行播放    <param name="intRecv">字節數組長度</param>    <param name="bytRecv">包含音頻數據的字節數組</param>  ------------------------------------- (3-3)
        public void GetVoiceData(int intRecv, byte[] bytRecv, bool listener, int pan_val, int vol, PictureBox ShowVoice)
        {
            //new Bitmap(Properties.Resources.Voice);
            // intPosWrite指示最新的數據寫好後的末尾。 intPosPlay指示本次播放開始的位置。
            if (intPosWrite + intRecv <= memstream.Capacity)
            {
                // 如果當前寫指針所在的位移 + 將要寫入到緩衝區長度小於缓衝區總大小
                if ((intPosWrite - intPosPlay >= 0 && intPosWrite - intPosPlay < intNotifySize) || (intPosWrite - intPosPlay < 0 && intPosWrite - intPosPlay + memstream.Capacity < intNotifySize))
                {
                    memstream.Write(bytRecv, 0, intRecv);
                    intPosWrite += intRecv;
                }
                else if (intPosWrite - intPosPlay >= 0)
                {
                    // 先儲存一定量的數據,當達到一定數據量時就播放聲音。
                    buffDiscript.BufferBytes = intPosWrite - intPosPlay;  // 缓衝區大小為播放指針到寫指針之間的距離。
                    SecondaryBuffer sec = new SecondaryBuffer(buffDiscript, PlayDev);  // 建立一個合適的缓衝區用於播放這段數據。
                    sec.Volume = vol;  // 聲音大小, 設定為最大聲
                    if (!listener)  // 若此資料是偶聽者的資料
                        if (sec.Volume == -500)  // 若為在後面者
                            sec.Volume = -1000;  // 聲音大小聲再降低
                    sec.Pan = pan_val;  // 左聲道 max_value -10000, 右聲道 max_value 10000
                    memstream.Position = intPosPlay;  // 先將memstream的指針定位到達一次播放開始的位置
                    sec.Write(0, memstream, intPosWrite - intPosPlay, LockFlag.FromWriteCursor);
                    sec.Play(0, BufferPlayFlags.Default);  // 播放聲音
                    memstream.Position = intPosWrite;  // 寫完後重新將memstream的指針定位到將要寫下去的位置。
                    intPosPlay = intPosWrite;
                    ShowVoice.Image = new Bitmap(Properties.Resources.Voice);
                }
                else if (intPosWrite - intPosPlay < 0)
                {
                    buffDiscript.BufferBytes = intPosWrite - intPosPlay + memstream.Capacity;  // 缓衝區大小為播放指針到寫指針之間的距離。
                    SecondaryBuffer sec = new SecondaryBuffer(buffDiscript, PlayDev);  // 建立一個合適的缓衝區用於播放這段數據。
                    sec.Volume = vol;  // 聲音大小, 設定為最大聲
                    if (!listener)  // 若此資料是偶聽者的資料
                        if (sec.Volume == -500)  // 若為在後面者
                            sec.Volume = -1000;  // 聲音大小聲降低
                    sec.Pan = pan_val;  // 左聲道, 右聲道
                    memstream.Position = intPosPlay;
                    sec.Write(0, memstream, memstream.Capacity - intPosPlay, LockFlag.FromWriteCursor);
                    memstream.Position = 0;
                    sec.Write(memstream.Capacity - intPosPlay, memstream, intPosWrite, LockFlag.FromWriteCursor);
                    sec.Play(0, BufferPlayFlags.Default);  // 播放聲音
                    memstream.Position = intPosWrite;
                    intPosPlay = intPosWrite;
                    ShowVoice.Image = new Bitmap(Properties.Resources.Voice);
                }
            }
            else
            {
                // 當數據將要大於memstream可容納的大小時
                int irest = memstream.Capacity - intPosWrite;  // memstream中剩下的可容纳的字節數。
                memstream.Write(bytRecv, 0, irest);  // 先寫完這個內存流。
                memstream.Position = 0;  // 然後讓新的數據從memstream的0位置開始記錄
                memstream.Write(bytRecv, irest, intRecv - irest);  // 覆蓋舊的數據
                intPosWrite = intRecv - irest;  // 更新寫指針位置。寫指針指示下一個開始寫入的位置而不是上一次结束的位置,因此不用减一
            }
        }
Example #44
0
        private void button4_Click(object sender, EventArgs e)
        {
            //directX clicked
            dSound = new Device();
            dSound.SetCooperativeLevel(this, CooperativeLevel.Priority);
            SecondaryBuffer sound;
            BufferDescription d = new BufferDescription();

            // Set descriptor’s flags
            d.ControlPan = true;
            d.ControlVolume = true;
            d.ControlFrequency = true;
            d.ControlEffects = true;

            sound = new SecondaryBuffer("C:\\Users\\Rafal\\Documents\\Visual Studio 2015\\Projects\\WindowsFormsApplication1\\v.wav", d, dSound);
            sound.Play(0, BufferPlayFlags.Default);
        }
Example #45
0
        public void Run()
        {
            S_RNDR();
            // generate sound

            sounddevice = new Device();
            sounddevice.SetCooperativeLevel(Program.F1, CooperativeLevel.Normal);
            //	Console.WriteLine("sounddevice = " + sounddevice);

            WaveFormat wf = new WaveFormat();
            wf.FormatTag = WaveFormatTag.Pcm;
            wf.SamplesPerSecond = 44100;
            wf.BitsPerSample = 16;
            wf.Channels = 1;
            wf.BlockAlign = 2;// (short)(wf.Channels * wf.BitsPerSample / 8);
            wf.AverageBytesPerSecond = 88200;// 88200;// wf.SamplesPerSecond * wf.BlockAlign;

            BufferDescription bufferDesc = new BufferDescription(wf);
            bufferDesc.BufferBytes = S_B.Length;
            bufferDesc.GlobalFocus = true;
            bufferDesc.ControlEffects = true;

            buffer = new SecondaryBuffer(bufferDesc, sounddevice);
            /*
            EffectDescription[] effects = new EffectDescription[2];
            effects[0].GuidEffectClass = DSoundHelper.StandardEchoGuid;
            //	effects[].GuidEffectClass = DSoundHelper.StandardFlangerGuid;
            effects[1].GuidEffectClass = DSoundHelper.StandardCompressorGuid;
            buffer.SetEffects(effects);

            EchoEffect ee = buffer.GetEffects(0) as EchoEffect;
            if (ee != null)
            {
                EffectsEcho ep = ee.AllParameters;
                ep.Feedback = 76.0f;
                ep.WetDryMix = 10.0f;
                ep.LeftDelay = 60000.0f / BPM / 4.0f * 3.0f;
                ep.RightDelay = 60000.0f / BPM / 4.0f * 3.0f;
                ep.PanDelay = 0;
                ee.AllParameters = ep;
            }
            */
            /*
            DistortionEffect de = buffer.GetEffects(0) as DistortionEffect;
            if (de != null)
            {
                EffectsDistortion ep = de.AllParameters;
                ep.PreLowpassCutoff = 8000.0f;
                ep.PostEqBandwidth = 4000.0f;
                ep.PostEqCenterFrequency = 4000.0f;
                ep.Edge = 0.0f;
                ep.Gain = 0.0f;
                de.AllParameters = ep;
            }*/

            buffer.Write(0, S_B, LockFlag.None);
            buffer.Play(0, BufferPlayFlags.Default);
            //	Console.WriteLine("buffer = " + buffer);

            //	Console.WriteLine("Running DemoThread...");
        }
Example #46
0
 public static void Play(string name)
 {
     if (!PlaySound) return;
     /*BUFFER[name].Stop();
     BUFFER[name].SetCurrentPosition(0);
     BUFFER[name].Play(0, BufferPlayFlags.Default);*/
     STREAM[name].Position = 0;
     SecondaryBuffer buffer = new SecondaryBuffer(STREAM[name], DEVICE);
     buffer.Stop();
     buffer.SetCurrentPosition(0);
     buffer.Play(0, BufferPlayFlags.Default);
     BUFFER_POOL.Add(new MyBuffer(buffer));
 }
Example #47
0
        private void AudioPlay()
        {
            if (AudioState == ReproductionState.Play)
            {
                try
                {
                    AudioActualPosition_Refresh.Enabled = false;
                    AudioState = ReproductionState.Stop;
                    audio.Stop();
                    audio.Dispose();
                    audio = null;
                }
                catch { }
                return;
            }
            else // estabamos parados, podemos seguir ._.
            {

                if (AudioGrid_Inicio != -1)
                {

                    /*
                     * CAMBIAR ESTO PARA COMPROBAR SI TIEMPO = 0
                     */
                    if (AudioGrid_Fin <= AudioGrid_Inicio)
                        AudioGrid_Fin = -1;

                    if (AudioTemp != null)
                    {
                        AudioTemp = new byte[0];
                        GC.Collect();
                    }

                    if (audio != null)
                    {
                        try
                        {
                            audio.Stop();
                            audio.Dispose();
                        }
                        catch { }
                    }

                    try
                    {

                        double inicio = Tiempo.TimeToSecondDouble(textInicio.Text);
                        InicioPlay = inicio;
                        double fin = 0;
                        if (AudioGrid_Fin != -1)
                            fin = Tiempo.TimeToSecondDouble(textFin.Text);

                        unsafe
                        {

                            byte* buf = (byte*)AudioFull.ToPointer();
                            byte* buf_final = buf;
                            buf += (int)(inicio * avsaudio.AudioSampleRate * avsaudio.BytesPerSample);

                            IntPtr tmp = new IntPtr(buf);
                            int tesuto = tmp.ToInt32();

                            if ((tesuto % 2) == 1) buf++;

                            if (AudioGrid_Fin != -1)
                            {
                                int max_or_mult = (int)Math.Min((int)(fin * avsaudio.AudioSampleRate * avsaudio.BytesPerSample), mainW.idx0rz);
                                buf_final += max_or_mult;
                            }
                            else
                                buf_final += mainW.idx0rz;

                            int size = (int)(buf_final - buf); // OJO
                            if ((size * (int)AudioMultiplicadorBuffer.Value) < mainW.idx0rz)
                                size = size * (int)AudioMultiplicadorBuffer.Value;

                            if (size < 0) return;

                            AudioTemp = new byte[size];
                            IntPtr buff = new IntPtr(buf);

                            Marshal.Copy(buff, AudioTemp, 0, size);
                            audio = avs2ds.PreparaAudio(AudioTemp);
                            audio.Play(0, BufferPlayFlags.Default);
                            AudioState = ReproductionState.Play;

                            AudioActualPosition_Refresh.Interval = (int)AudioActualPositionInterval.Value * 10;
                            AudioActualPosition_Refresh.Enabled = true;
                        }
                    }
                    catch { }
                }
            }
        }
Example #48
0
        private void AudioPlayEx(PlayOptions options)
        {
            if (AudioState == ReproductionState.Play)
            {
                AudioActualPosition_Refresh_500.Enabled = false;
                AudioState = ReproductionState.Stop;
                audio.Stop();
                audio.Dispose();
                audio = null;
                return;
            }

            double inicio = Tiempo.TimeToSecondDouble(textInicio.Text);
            double fin = 0;

            if (AudioGrid_Inicio == -1) return;

            if (AudioGrid_Fin != -1)
                fin = Tiempo.TimeToSecondDouble(textFin.Text);
            else
                if (options == PlayOptions.BeforeEnd || options == PlayOptions.AfterEnd)
                    return;

            switch (options)
            {
                case PlayOptions.BeforeStart:

                    if (inicio < .5)
                    {
                        inicio = 0;
                        fin = .5;
                    }
                    else
                    {
                        inicio -= .5;
                        fin = inicio + .5;
                    }

                    break;
                case PlayOptions.AfterStart:
                    fin = inicio + .5;
                    break;

                case PlayOptions.BeforeEnd:
                    fin = Tiempo.TimeToSecondDouble(textFin.Text);
                    inicio = fin - .5;

                    if (inicio < 0) inicio = 0;
                    break;
                case PlayOptions.AfterEnd:
                    inicio = Tiempo.TimeToSecondDouble(textFin.Text);
                    fin = inicio + .5;

                    break;
                case PlayOptions.Normal:
                    inicio = Tiempo.TimeToSecondDouble(textInicio.Text);
                    fin = Tiempo.TimeToSecondDouble(textFin.Text);
                    break;
            }

            audioGrid_Inicio_500 = inicio;
            audioGrid_Fin_500 = fin;

            InicioPlay = inicio;

            unsafe
            {

                byte* buf = (byte*)AudioFull.ToPointer();
                byte* buf_final = buf;
                buf += (int)(inicio * avsaudio.AudioSampleRate * avsaudio.BytesPerSample);

                IntPtr tmp = new IntPtr(buf);
                int tesuto = tmp.ToInt32();

                if ((tesuto % 2) == 1) buf++;

                //if (tesuto >= mainW.idx0rz) return;

                int max_or_mult = (int)Math.Min((int)(fin * avsaudio.AudioSampleRate * avsaudio.BytesPerSample), mainW.idx0rz);
                buf_final += max_or_mult;

                int size = (int)(buf_final - buf);

                if (size < 0) return;

                AudioTemp = new byte[size];
                IntPtr buff = new IntPtr(buf);

                Marshal.Copy(buff, AudioTemp, 0, size);
                audio = avs2ds.PreparaAudio(AudioTemp);
                audio.Play(0, BufferPlayFlags.Default);
                AudioState = ReproductionState.Play;
                AudioActualPosition_Refresh_500.Enabled = true;
            }
        }
Example #49
0
 private void PlayFrame(byte[] data)
 {
     try
     {
         playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);
         if (ConfSingleton.Instance.Compression)
         {
             byte[] byteDecodedData = new byte[data.Length * 2];
             ALawDecoder.ALawDecode(data, out byteDecodedData);
             playbackBuffer.Write(0, byteDecodedData, LockFlag.None);
         }
         else
         {
             playbackBuffer.Write(0, data, LockFlag.None);
         }
         playbackBuffer.Play(0, BufferPlayFlags.Default);
     }
     catch (Exception)
     {
         RefreshSoundDevice();
     }
 }
        /*
         * Receive audio data coming on port 1550 and feed it to the speakers to be played.
         */
        private void Receive()
        {
            try
            {
                bStop = false;
                IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);

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

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

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

                    //Play the data received to the user.
                    playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);
                    playbackBuffer.Write(0, byteDecodedData, LockFlag.None);
                    playbackBuffer.Play(0, BufferPlayFlags.Default);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "VoiceChat-Receive ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                nUdpClientFlag += 1;
            }
        }
Example #51
0
        /*
          * Receive audio data coming on port 1550 and feed it to the speakers to be played.
          */
        private void Receive()
        {
            try
             {

                 IsThreadReceiveEnd = false;

                 byte[] byteData;
                 bStop = false;
                 IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);

                 if (eMode == Mode.Server)
                 {
                     LogAppend("Server Started");
                     LogUsersConnected();
                 }
                 else
                     LogAppend("Client Audio Connected");

                 while (!bStop)
                 {
                     //Receive data.
                     try
                     {

                         //bytes_received = udp_socket.ReceiveFrom(data, ref ep);

                         try
                         {
                             byteData = udpClient.Receive(ref remoteEP);
                         }
                         catch (Exception)
                         {
                             return;
                         }

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

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

                         if (eMode == Mode.Server)
                         {
                             lock (otherPartyIPs)
                             {
                                 for (int i = 0; i < otherPartyIPs.Count; i++)
                                     udpClient.Send(byteDecodedData, byteDecodedData.Length, otherPartyIPs[i].Address.ToString(), 1550);

                             }

                         }

                         //Play the data received to the user.
                         playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);
                         playbackBuffer.Write(0, byteDecodedData, LockFlag.None);
                         playbackBuffer.Play(0, BufferPlayFlags.Default);
                     }
                     catch (Exception)
                     {

                     }

                 }

                 if (eMode == Mode.Server)
                 {
                     LogAppend("Server Stopped");
                     LogUsersConnected();
                 }
                 else
                     LogAppend("Client Audio Disconnected");

             }
             catch (Exception ex)
             {

                 LogAppend("Voice Receive > " + ex.Message);
                 //MessageBox.Show(ex.Message, "VoiceChat-Receive ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
             finally
             {
                 nUdpClientFlag += 1;
             }

             IsThreadReceiveEnd = true;
        }
Example #52
0
 /// <summary>
 /// Plays sound. 
 /// </summary>
 /// <param name="e">Sound to play</param>
 public static void play(Sound e)
 {
     MemoryStream ms = e.getStream();
     SecondaryBuffer buffer = new SecondaryBuffer(ms, device);
     buffer.Play(0, BufferPlayFlags.Default);
 }
Example #53
0
 private void button1_Click(object sender, System.EventArgs e)
 {
     if (spc != null || snd!=null)
     {
         Device dev = getDev();
         BufferDescription desc = new BufferDescription(WavFile.getFormat());
         desc.ControlVolume = true;
         desc.Flags = BufferDescriptionFlags.ControlVolume;
         byte[] raw = snd==null?spc.getWave().rawBytes():snd.getWave().rawBytes();
         desc.BufferBytes = raw.Length;
         SecondaryBuffer buf = new SecondaryBuffer(desc, dev);
         buf.Write(0, raw, LockFlag.EntireBuffer);
         buf.SetCurrentPosition(0);
         buf.Volume = 0;
         buf.Play(0, BufferPlayFlags.Default);
     }
 }
Example #54
0
        private static void PlayThread(object osn)
        {
            EmulatorForm myform = (EmulatorForm)osn;

            SecondaryBuffer SecBuf;
            AutoResetEvent SecBufNotifyAtHalf = new AutoResetEvent(false);
            AutoResetEvent SecBufNotifyAtBeginning = new AutoResetEvent(false);
            
            int SamplingRate = (int)myform._samplingRate;
            int HoldThisManySamples = (int)(1 * SamplingRate);
            int BlockAlign = 2;
            int SecBufByteSize = HoldThisManySamples * BlockAlign;

            WaveFormat MyWaveFormat = new WaveFormat();

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

            BufferDescription MyDescription;

            // Set BufferDescription
            MyDescription = new BufferDescription();

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

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

            Notify MyNotify;

            MyNotify = new Notify(SecBuf);

            BufferPositionNotify[] MyBufferPositions = new BufferPositionNotify[2];

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

            MyNotify.SetNotificationPositions(MyBufferPositions);

            WaitHandle[] SecBufWaitHandles = { SecBufNotifyAtBeginning, SecBufNotifyAtHalf };
            
            Int16[] buffer;

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

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

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

                    buffer = myform._sn.GenerateSamples((uint)WriteCount/2, "");
                    
                    SecBuf.Write(
                        SecBufNextWritePosition,
                        buffer,
                        LockFlag.None);

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

            SecBuf.Dispose();
            MyDescription.Dispose();
            MyNotify.Dispose();

        }
Example #55
0
 public static void Play(string path)
 {
     try
     {
         SecondaryBuffer sound = new SecondaryBuffer(path, _description, _device);//= mxAudioCache.GetInstance.Get(path);
         if (sound != null) sound.Play(0, BufferPlayFlags.Default);
     }
     catch (Exception e) { System.Windows.Forms.MessageBox.Show("Invalid audio file!\n" + e); }
 }