private void readGarbageFromWave()
        {
            if (waveStream != null)
            {
                waveStream.Position = 0;
                var buffer = new byte[BlockAlign(256)];

                for (int x = 0; x < 10; x++)
                {
                    waveStream.Read(buffer, 0, buffer.Length);
                }
            }
        }
Esempio n. 2
0
        private int LoadStream(WaveStream waveStream)
        {
            if (!isInitialized)
            {
                Error("Trying to Load Stream format for uninitialized sound manager");
            }

            int channels, bits_per_sample, sample_rate;

            byte[] sound_data = null;

            for (int i = 0; i < managedSounds.Count; ++i)
            {
                if (managedSounds[i].refCount <= 0)
                {
                    StopSound(i);
                    AL.DeleteBuffer(managedSounds[i].bufferHandle);
                    managedSounds[i].bufferHandle = AL.GenBuffer();
                    managedSounds[i].refCount     = 1;

                    sound_data = new byte[waveStream.Length];
                    waveStream.Read(sound_data, 0, (int)waveStream.Length);
                    channels        = waveStream.WaveFormat.Channels;
                    bits_per_sample = waveStream.WaveFormat.BitsPerSample;
                    sample_rate     = waveStream.WaveFormat.SampleRate;
                    AL.BufferData(managedSounds[i].bufferHandle, GetSoundFormat(channels, bits_per_sample), sound_data, sound_data.Length, sample_rate);
                    AL.Source(managedSounds[i].soundSource, ALSourcei.Buffer, managedSounds[i].bufferHandle);

                    return(i);
                }
            }

            SoundInstance newSound = new SoundInstance();

            newSound.refCount     = 1;
            newSound.bufferHandle = AL.GenBuffer();
            newSound.soundSource  = AL.GenSource();

            sound_data = new byte[waveStream.Length];
            waveStream.Read(sound_data, 0, (int)waveStream.Length);
            channels        = waveStream.WaveFormat.Channels;
            bits_per_sample = waveStream.WaveFormat.BitsPerSample;
            sample_rate     = waveStream.WaveFormat.SampleRate;
            AL.BufferData(newSound.bufferHandle, GetSoundFormat(channels, bits_per_sample), sound_data, sound_data.Length, sample_rate);
            AL.Source(newSound.soundSource, ALSourcei.Buffer, newSound.bufferHandle);

            managedSounds.Add(newSound);
            return(managedSounds.Count - 1);
        }
        private static MemoryStream Hide(string s, WaveStream sourceStream)
        {
            int messageLength = s.Length;

            byte[] length = BitConverter.GetBytes(messageLength);

            byte[] messageByte = Encoding.UTF8.GetBytes(s);
            byte[] merge       = new byte[length.Length + messageByte.Length];
            Buffer.BlockCopy(length, 0, merge, 0, length.Length);
            Buffer.BlockCopy(messageByte, 0, merge, length.Length, messageByte.Length);
            Stream messageStream  = new MemoryStream(merge);
            int    bytesPerSample = 2;

            byte[] waveBuffer = new byte[bytesPerSample];
            byte   message, bit, waveByte;
            int    messageBuffer;

            while ((messageBuffer = messageStream.ReadByte()) >= 0)
            {
                message = (byte)messageBuffer;

                for (int bitIndex = 0; bitIndex < 8; bitIndex++)
                {
                    sourceStream.Read(waveBuffer, 0, waveBuffer.Length);
                    waveByte = waveBuffer[bytesPerSample - 1];

                    bit = (byte)(((message & (byte)(1 << bitIndex)) > 0) ? 1 : 0);

                    if ((bit == 1) && ((waveByte % 2) == 0))
                    {
                        waveByte += 1;
                    }
                    else if ((bit == 0) && ((waveByte % 2) == 1))
                    {
                        waveByte -= 1;
                    }

                    waveBuffer[bytesPerSample - 1] = waveByte;

                    destinationStream.Write(waveBuffer, 0, bytesPerSample);
                }
            }
            waveBuffer = new byte[sourceStream.Length - sourceStream.Position];
            sourceStream.Read(waveBuffer, 0, waveBuffer.Length);
            destinationStream.Write(waveBuffer, 0, waveBuffer.Length);
            destinationStream = WaveStream.CreateStream(destinationStream, sourceStream.Format);
            return(destinationStream);
        }
Esempio n. 4
0
        private static byte[] MP3BytesToWavBytes(byte[] input, WaveFormat outputFormat = null)
        {
            byte[] retval = null;

            using (MemoryStream outputStream = new MemoryStream())
                using (MemoryStream inputStream = new MemoryStream(input))
                    using (WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(inputStream)))
                    {
                        if (outputFormat == null)
                        {
                            outputFormat = waveStream.WaveFormat;
                        }
                        using (WaveFileWriter waveFileWriter = new WaveFileWriter(outputStream, outputFormat))
                        {
                            byte[] bytes = new byte[waveStream.Length];
                            waveStream.Position = 0;
                            waveStream.Read(bytes, 0, (int)waveStream.Length);
                            waveFileWriter.Write(bytes, 0, bytes.Length);
                            waveFileWriter.Flush();

                            outputStream.Position = 0;
                            retval = outputStream.ToArray();
                        }
                    }
            return(retval);
        }
Esempio n. 5
0
        public Byte[] WavToMP3(WaveStream ws)//byte[] wavFile)
        {
            //using (MemoryStream source = new MemoryStream(wavFile))
            //using (NAudio.Wave.WaveFileReader rdr = new NAudio.Wave.WaveFileReader(source))
            {
                WaveLib.WaveFormat fmt = new WaveLib.WaveFormat(SampleRate, BitsPerSample, Channels);
                //new WaveLib.WaveFormat(rdr.WaveFormat.SampleRate, rdr.WaveFormat.BitsPerSample, rdr.WaveFormat.Channels);

                // convert to MP3 at 96kbit/sec...
                Yeti.Lame.BE_CONFIG conf = new Yeti.Lame.BE_CONFIG(fmt, 96);

                // Allocate a 1-second buffer
                int    blen   = ws.WaveFormat.AverageBytesPerSecond;
                byte[] buffer = new byte[blen];

                // Do conversion
                using (MemoryStream output = new MemoryStream())
                {
                    Yeti.MMedia.Mp3.Mp3Writer mp3 = new Yeti.MMedia.Mp3.Mp3Writer(output, fmt, conf);

                    int readCount;
                    while ((readCount = ws.Read(buffer, 0, blen)) > 0)
                    {
                        mp3.Write(buffer, 0, readCount);
                    }

                    mp3.Close();
                    return(output.ToArray());
                }
            }
        }
Esempio n. 6
0
        public short[] GetDataOf16Bit2ChannelFile(WaveStream reader)
        {
            reader.Seek(0, System.IO.SeekOrigin.Begin);
            byte[] data2 = new byte[reader.Length];
            reader.Read(data2, 0, data2.Length);

            short[] res2 = new short[data2.Length / 2];
            Buffer.BlockCopy(data2, 0, res2, 0, data2.Length);

            return(res2);

            /*
             * reader.Seek(0, System.IO.SeekOrigin.Begin);
             * byte[] data = new byte[reader.Length];
             * reader.Read(data, 0, data.Length);
             * short[] res = new short[data.Length / 2];
             * for (int i = 0; i < data.Length; i += 2)
             *  res[i / 2] = BitConverter.ToInt16(data, i);
             *
             *
             * // do we have the same sequence?
             * Debug.WriteLine(res.SequenceEqual(res2));    // True
             *
             * return res;
             */
        }
Esempio n. 7
0
        private void Decode(IAudioConsumer consumer, int maxLength)
        {
            int remaining, length, size;

            byte[]  buffer = new byte[2 * BUFFER_SIZE];
            short[] data   = new short[BUFFER_SIZE];

            // Samples to read to get maxLength seconds of audio
            remaining = maxLength * channels * sampleRate;

            // Bytes to read
            length = 2 * Math.Min(remaining, BUFFER_SIZE);

            while ((size = reader.Read(buffer, 0, length)) > 0)
            {
                Buffer.BlockCopy(buffer, 0, data, 0, size);

                consumer.Consume(data, size / 2);

                remaining -= size / 2;
                if (remaining <= 0)
                {
                    break;
                }

                length = 2 * Math.Min(remaining, BUFFER_SIZE);
            }
        }
Esempio n. 8
0
        private void BackgroundPlayer_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            object[] arguments = e.Argument as object[];

            WaveStream WaveFloat = (WaveStream)arguments[0];
            int        LeftPos   = Conversions.ToInteger(arguments[1]);
            int        RightPos  = Conversions.ToInteger(arguments[2]);
            var        bytes     = new byte[RightPos - LeftPos + 1];

            WaveFloat.Position = LeftPos;
            WaveFloat.Read(bytes, 0, RightPos - LeftPos);
            WaveFloat = new RawSourceWaveStream(new MemoryStream(bytes), WaveFloat.WaveFormat);
            // WaveFloat.PadWithZeroes = False

            using (var output = new WaveOutEvent())
            {
                output.Init(WaveFloat);
                output.Play();
                while (output.PlaybackState == PlaybackState.Playing & !BackgroundPlayer.CancellationPending)
                {
                    Thread.Sleep(45);
                    BackgroundPlayer.ReportProgress((int)(output.GetPosition() / (WaveFloat.WaveFormat.BitsPerSample / 8d)));
                }
            }
        }
Esempio n. 9
0
        public override int Read(byte[] buffer, int offset, int count)
        {
            int totalBytesRead = 0;

            while (totalBytesRead < count)
            {
                int bytesRead = sourceStream.Read(buffer, offset + totalBytesRead, count - totalBytesRead);

                if (bytesRead == 0)
                {
                    if (sourceStream.Position == 0 || !EnableLooping)
                    {
                        // something wrong with the source stream
                        //CHAPUZA PARA INDICAR EL FINAL DEL STREAM:
                        //new Reproductor().StreamFinalizado = false;
                        break;
                    }

                    // loop
                    sourceStream.Position = 0;
                }

                totalBytesRead += bytesRead;
            }

            return(totalBytesRead);
        }
Esempio n. 10
0
        /// <summary>
        /// <see cref="Control.OnPaint"/>
        /// </summary>
        protected override void OnPaint(PaintEventArgs e)
        {
            if (waveStream != null)
            {
                waveStream.Position = 0;
                int bytesRead;
                byte[] waveData = new byte[samplesPerPixel * bytesPerSample];
                waveStream.Position = startPosition + (e.ClipRectangle.Left * bytesPerSample * samplesPerPixel);

                for (float x = e.ClipRectangle.X; x < e.ClipRectangle.Right; x += 1)
                {
                    short low = 0;
                    short high = 0;
                    bytesRead = waveStream.Read(waveData, 0, samplesPerPixel * bytesPerSample);
                    if (bytesRead == 0)
                        break;
                    for (int n = 0; n < bytesRead; n += 2)
                    {
                        short sample = BitConverter.ToInt16(waveData, n);
                        if (sample < low) low = sample;
                        if (sample > high) high = sample;
                    }
                    float lowPercent = ((((float) low) - short.MinValue) / ushort.MaxValue);
                    float highPercent = ((((float) high) - short.MinValue) / ushort.MaxValue);
                    e.Graphics.DrawLine(Pens.Black, x, this.Height * lowPercent, x, this.Height * highPercent);
                }
            }

            base.OnPaint(e);
        }
Esempio n. 11
0
        public override bool Decode(IAudioConsumer consumer, int maxLength)
        {
            if (reader == null)
            {
                return(false);
            }

            int remaining, length, size;

            byte[]  buffer = new byte[2 * BUFFER_SIZE];
            short[] data   = new short[BUFFER_SIZE];

            // Samples to read to get maxLength seconds of audio
            remaining = maxLength * this.Format.Channels * this.sampleRate;

            // Bytes to read
            length = 2 * Math.Min(remaining, BUFFER_SIZE);

            while ((size = reader.Read(buffer, 0, length)) > 0)
            {
                Buffer.BlockCopy(buffer, 0, data, 0, size);

                consumer.Consume(data, size / 2);

                remaining -= size / 2;
                if (remaining <= 0)
                {
                    break;
                }

                length = 2 * Math.Min(remaining, BUFFER_SIZE);
            }

            return(true);
        }
Esempio n. 12
0
        public SoundLibrary(int index, string fileName, bool loop)
        {
            Index = index;

            fileName = Path.Combine(Settings.SoundPath, fileName);
            if (!File.Exists(fileName))
            {
                return;
            }

            _stream = new WaveStream(fileName);

            _desc = new SoundBufferDescription
            {
                SizeInBytes = (int)_stream.Length,
                Flags       = BufferFlags.ControlVolume | BufferFlags.ControlPan | BufferFlags.GlobalFocus,
                Format      = _stream.Format
            };

            _data = new byte[_desc.SizeInBytes];
            _stream.Read(_data, 0, (int)_stream.Length);

            _loop = loop;

            _bufferList = new List <SecondarySoundBuffer>();

            Play();
        }
Esempio n. 13
0
            public override int Read(byte[] buffer, int offset, int count)
            {
                long baseStreamLength = _baseStream.Length;

                // Read base stream
                int readInTotal = 0;

                if (_currentPosition < baseStreamLength)
                {
                    int read = _baseStream.Read(buffer, offset, count);
                    offset           += read;
                    count            -= read;
                    _currentPosition += read;
                    readInTotal      += read;
                }

                // Extend base stream with new samples
                if (_currentPosition >= baseStreamLength)
                {
                    int extraByteCount = (int)(_extendedLengthInBytes - _currentPosition);
                    int read           = Math.Min(extraByteCount, count);
                    Array.Clear(buffer, offset, read);
                    offset           += read;
                    count            -= read;
                    _currentPosition += read;
                    readInTotal      += read;
                }

                return(readInTotal);
            }
Esempio n. 14
0
        private void Stream(WaveStream stream, CancellationToken cancellationToken)
        {
            var buffer          = new byte[stream.WaveFormat.AverageBytesPerSecond];
            var streamTimeStart = stream.CurrentTime;
            var realTimeStart   = DateTime.UtcNow;

            while (!cancellationToken.IsCancellationRequested)
            {
                var bytesRead = stream.Read(buffer, 0, buffer.Length);

                if (bytesRead == 0)
                {
                    // if we have reached the end, reset stream to start
                    stream.CurrentTime = TimeSpan.Zero;
                    streamTimeStart    = stream.CurrentTime;
                    realTimeStart      = DateTime.UtcNow;
                    continue;
                }

                var time        = realTimeStart + stream.CurrentTime;
                var audioSample = new AudioSample
                {
                    Timestamp = time.ToString("o"),
                    Data      = ByteString.CopyFrom(buffer)
                };
                OnAudioSampleCreated(audioSample);

                var streamTimePassed = stream.CurrentTime - streamTimeStart;
                var realTimePassed   = DateTime.UtcNow - realTimeStart;
                var timeDifference   = Math.Max(0, (streamTimePassed - realTimePassed).TotalMilliseconds);
                Thread.Sleep((int)timeDifference);
            }
        }
Esempio n. 15
0
        public Bitmap GetWaveform(string filename, Stream inputStream)
        {
            WaveStream reader = getReader(filename, inputStream);

            List <float> data = null;


            if (reader is Mp3FileReader)
            {
                long   sizeOfStream = reader.Length;
                byte[] stream       = new byte[sizeOfStream];
                reader.Read(stream, 0, (int)sizeOfStream);
                data = getMp3WaveForm(stream, sizeOfStream);
                reader.Close();
            }
            else
            {// we have a wav file reader
                data = getWavWaveForm(reader as WaveFileReader);
            }



            Bitmap image = DrawNormalizedAudio(data, this.ForegroundColor, this.BackgroundColor, new Size(this.Width, this.Height));

            return(image);
        }
Esempio n. 16
0
        WAV ConvertMP3DataToWAV(byte[] mp3Data)
        {
            using (MemoryStream mp3Stream = new MemoryStream(mp3Data))
            {
                using (Mp3FileReader mp3Audio = new Mp3FileReader(mp3Stream))
                {
                    using (WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(mp3Audio))
                    {
                        using (MemoryStream outputStream = new MemoryStream())
                        {
                            using (WaveFileWriter waveFileWriter = new WaveFileWriter(outputStream, waveStream.WaveFormat))
                            {
                                byte[] bytes = new byte[waveStream.Length];
                                waveStream.Position = 0;
                                waveStream.Read(bytes, 0, Convert.ToInt32(waveStream.Length));
                                waveFileWriter.Write(bytes, 0, bytes.Length);
                                waveFileWriter.Flush();
                            }

                            return(new WAV(outputStream.ToArray()));
                        }
                    }
                }
            }
        }
Esempio n. 17
0
        private int ReadFromSegment(byte[] buffer, int offset, int count)
        {
            var bytesAvailable = (int)(segmentStart + segmentDuration - sourceStream.Position);
            var bytesRequired  = Math.Min(bytesAvailable, count);

            return(sourceStream.Read(buffer, offset, bytesRequired));
        }
Esempio n. 18
0
 protected override void AppendProperties()
 {
     byte[] raw = new byte[ms.Length];
     ms.Read(raw, 0, raw.Length);
     this.Value = Convert.ToBase64String(raw, 0, (int)ms.Length);
     base.AppendProperties();
 }
Esempio n. 19
0
        public static byte[] WaveStreamToArray(WaveStream stream)
        {
            if (stream == null)
            {
                return(null);
            }
            else if (stream.Length == 0)
            {
                return(new byte[0]);
            }

            byte[] buff = new byte[stream.Length];

            MemoryStream memory = new MemoryStream();
            int          reader = 0;

            stream.Position = 0;
            while ((reader = stream.Read(buff, 0, buff.Length)) != 0)
            {
                memory.Write(buff, 0, reader);
            }

            stream.Position = 0;

            return(memory.ToArray());
        }
Esempio n. 20
0
        private static void mp3izza(string nomefile, string nomefilemp3)
        {
            WaveStream filewav = new WaveStream(nomefile);
            //      try
            //      {
            Mp3Writer salvamp3 = new Mp3Writer(new FileStream(nomefilemp3,
                                                              FileMode.Create), filewav.Format);

            //          try
            //          {
            byte[] buff = new byte[salvamp3.OptimalBufferSize];
            int    read = 0;

            while ((read = filewav.Read(buff, 0, buff.Length)) > 0)
            {
                salvamp3.Write(buff, 0, read);
            }
            //         }
            //         finally
            //         {
            salvamp3.Close();
            //         }
            //     }
            //     finally
            //     {
            filewav.Close();
            //     }
            File.Delete(nomefile);
        }
Esempio n. 21
0
        public override int Read(byte[] buffer, int offset, int count)
        {
            int totalBytesRead = 0;

            while (totalBytesRead < count && Loop > 0)
            {
                if (stop)
                {
                    log.Debug("stop sound");
                    return(0);
                }

                int bytesRead = sourceStream.Read(buffer, offset + totalBytesRead, count - totalBytesRead);

                if (bytesRead == 0)
                {
                    if (sourceStream.Position == 0 && Loop <= 0)
                    {
                        log.Debug("end of file");
                        break;
                    }

                    // loop
                    Loop--;
                    sourceStream.Position = 0;
                }

                totalBytesRead += bytesRead;
            }

            return(totalBytesRead);
        }
Esempio n. 22
0
        public void Start(AudioVideoFlow flow, LyncServer server)
        {
            _flow   = flow;
            _server = server;

            Recorder recorder = new Recorder();

            recorder.AttachFlow(_flow);
            WmaFileSink sink = new WmaFileSink("voice_input.wma");

            recorder.SetSink(sink);
            recorder.Start();

            var        wmafileReader = new WMAFileReader("voice_input.wma");
            WaveStream waveStream    = WaveFormatConversionStream.CreatePcmStream(wmafileReader);
            int        reader        = 0;

            byte[] buffer = new byte[4096];
            var    header = GetWaveHeader(waveStream.WaveFormat);

            _speech.SendMessage(new ArraySegment <byte>(header, 0, header.Length));

            while ((reader = waveStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                AudioDataAvailable(new ArraySegment <byte>(buffer, 0, buffer.Length));
                Thread.Sleep(10);
            }
        }
Esempio n. 23
0
 private void ReadSamples(WaveStream waveStream)
 {
     if (data == null)
     {
         data = new byte[(int)waveStream.Length];
         waveStream.Read(data, 0, (int)waveStream.Length);
     }
 }
Esempio n. 24
0
        /// <summary>
        ///   Reads a maximum of count samples from the current stream, and writes the data to buffer, beginning at index.
        /// </summary>
        /// <param name="buffer">
        ///    When this method returns, this parameter contains the specified byte array with the values between index and (index + count -1) replaced by the 8 bit frames read from the current source.
        /// </param>
        /// <param name="count">The ammount of frames to read.</param>
        /// <returns>The number of reads performed on the stream.</returns>
        private int read(float[] buffer, int count)
        {
            int reads;

            int blockSize = sizeof(float) * count * channels;

            byte[] block = new byte[blockSize];
            reads = waveStream.Read(block, 0, blockSize);

            // Convert from byte to float
            for (int j = 0; j < bufferSize; j++)
            {
                buffer[j] = BitConverter.ToSingle(block, j * sizeof(float));
            }

            return(reads);
        }
Esempio n. 25
0
        public byte[] ReadAllBytes(WaveStream stream)
        {
            var data = new byte[stream.Length];

            stream.Position = 0;
            stream.Read(data, 0, data.Length);
            stream.Position = 0;
            return(data);
        }
Esempio n. 26
0
        /// <summary>
        /// Reads bytes from this wave stream
        /// </summary>
        /// <param name="destBuffer">Destination buffer</param>
        /// <param name="offset">Offset into destination buffer</param>
        /// <param name="numBytes"></param>
        /// <returns>Number of bytes read.</returns>
        public override int Read(byte[] destBuffer, int offset, int numBytes)
        {
            byte[] sourceBuffer = new byte[numBytes * 2];
            int    bytesRead    = sourceStream.Read(sourceBuffer, 0, numBytes * 2);

            Convert32To16(destBuffer, offset, sourceBuffer, bytesRead);
            position += (bytesRead / 2);
            return(bytesRead / 2);
        }
Esempio n. 27
0
        public override int Read(byte[] buffer, int offset, int count)
        {
            int bytesRequired = (int)Math.Min(count, Length - Position);
            int bytesRead     = 0;

            if (bytesRequired > 0)
            {
                bytesRead = source.Read(buffer, offset, bytesRequired);
            }
            return(bytesRead);
        }
Esempio n. 28
0
 public int Read(byte[] array, int offset, int count)
 {
     Debug.WriteLine(_stream.CurrentTime);
     if (_stream.CurrentTime > _end)
     {
         // back to start to loop
         // if you want to stop here, return 0 instead.
         _stream.CurrentTime = _start;
     }
     return(_stream.Read(array, offset, count));
 }
Esempio n. 29
0
        /// <summary>
        /// Read an audio file.
        /// </summary>
        void Read()
        {
            reader   = new MediaFoundationReader(fileName);
            duration = reader.TotalTime;
            format   = new AudioFormat(reader.WaveFormat);

            var bytes = new byte[reader.Length];
            var read  = reader.Read(bytes, 0, bytes.Length);

            data = new List <byte>(bytes);
        }
Esempio n. 30
0
        public int Read(byte[] buffer, int offset, int count)
        {
            int samples = sourceStream.Read(buffer, offset, count);

            for (int i = 0; i < count; i += offset)
            {
                float sample = BitConverter.ToSingle(buffer, i);
                sampleAggregator.Add(sample);
            }
            return(samples);
        }
Esempio n. 31
0
        /// <summary>
        /// Initializes a new WaveOutAudioSource class.
        /// </summary>
        /// <param name="waveStream">The WaveStream.</param>
        internal WaveOutAudioSource(WaveStream waveStream)
        {
            waveStream.Seek(0, SeekOrigin.Begin);
            WaveData = new byte[waveStream.Length];
            waveStream.Read(WaveData, 0, WaveData.Length);
            waveStream.Close();
            WaveFormat = waveStream.Format;

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

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

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

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

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

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

                Thread thread = new Thread(new ParameterizedThreadStart(DoPlay));
                thread.Start(buffer);
                if (!bAsync) thread.Join();
                return name;
            }
            catch (Exception ex)
            {
                Utilities.OnError(Utilities.GetCurrentMethod(), ex);
                return "";
            }
        }
Esempio n. 34
0
 private void DrawSegmentWaveform(string segmentFileName)
 {
     lock (this)
     {
         using (var stream = new WaveStream(segmentFileName))
         {
             var buffer = new byte[stream.Length];
             stream.Read(buffer, 0, (int) stream.Length);
             if (stream.FormatEx.wBitsPerSample == 8)
             {
                 ui.DrawSegment(buffer);
             }
             else
             {
                 IntPtr zero = IntPtr.Zero;
                 try
                 {
                     var destination = new short[buffer.Length/2];
                     zero = Marshal.AllocHGlobal(((Marshal.SizeOf(typeof (short))*buffer.Length)/2));
                     Marshal.Copy(buffer, 0, zero, buffer.Length);
                     Marshal.Copy(zero, destination, 0, buffer.Length/2);
                     ui.DrawSegment(destination);
                 }
                 finally
                 {
                     if (zero != IntPtr.Zero)
                     {
                         Marshal.FreeHGlobal(zero);
                     }
                 }
             }
         }
     }
 }