Exemplo n.º 1
2
 private void playButton_Click(object sender, EventArgs e)
 {
     waveOut = new WaveOut();
     waveOut.PlaybackStopped += waveOut_PlaybackStopped;
     reader = new WaveFileReader("sample.wav");
     waveOut.Init(reader);
     waveOut.Play();
 }
Exemplo n.º 2
0
		private void DisposeInputWave() {
			if (wavStream != null) {
				this.wavStream.Dispose();
				this.wavStream = null;
			}
			this.wavFileReader = null;
		}
Exemplo n.º 3
0
 private void playSound(String type, String dir)
 {
     DisposeWave();
     if (type.Equals("LETTER"))
     {
         wave   = new NAudio.Wave.WaveFileReader(dir);
         output = new NAudio.Wave.DirectSoundOut();
         output.Init(new NAudio.Wave.WaveChannel32(wave));
         output.Play();
     }
     else if (type.Equals("WON"))
     {
         wave   = new NAudio.Wave.WaveFileReader(dir);
         output = new NAudio.Wave.DirectSoundOut();
         output.Init(new NAudio.Wave.WaveChannel32(wave));
         output.Play();
     }
     else if (type.Equals("LOSE"))
     {
         wave   = new NAudio.Wave.WaveFileReader(dir);
         output = new NAudio.Wave.DirectSoundOut();
         output.Init(new NAudio.Wave.WaveChannel32(wave));
         output.Play();
     }
 }
Exemplo n.º 4
0
        public void PlayMusic(string sample, IAudioClient voiceClient)
        {
            using (WaveFileReader pcm = new WaveFileReader(sample))
            {
                int blocksize = pcm.WaveFormat.AverageBytesPerSecond / 5;
                byte[] buffer = new byte[blocksize];
                int offset = 0;

                    try
                    {
                        while (offset < pcm.Length / blocksize && !skip)
                        {
                            if (currentPlaying != sample)
                            {

                            }

                            offset++;
                            pcm.Read(buffer, 0, blocksize);

                            voiceClient.Send(buffer, 0, blocksize);
                            //voiceClient.Wait();
                        }
                    }
                    catch (Exception e)
                    {
                        Console.Write(e.ToString());
                    }
            }
            return;
        }
Exemplo n.º 5
0
        /// <summary>
        /// Merge multiple .wav files together and save the output.
        /// </summary>
        /// <param name="outputFile">The path to save the output to.</param>
        /// <param name="sourceFiles">An IEnumerable list of files to merge.</param>
        private static void ConcatenateWav(string outputFile, IEnumerable<string> sourceFiles) {
            byte[] buffer = new byte[1024];
            WaveFileWriter waveFileWriter = null;
            
            try {
                foreach (string sourceFile in sourceFiles) {
                    using (WaveFileReader reader = new WaveFileReader(sourceFile)) {
                        if (waveFileWriter == null) {
                            // first time in create new Writer
                            waveFileWriter = new WaveFileWriter(outputFile, reader.WaveFormat);
                        }
                        else {
                            if (!reader.WaveFormat.Equals(waveFileWriter.WaveFormat)) {
                                throw new InvalidOperationException("Can't concatenate WAV Files that don't share the same format");
                            }
                        }

                        int read;
                        while ((read = reader.Read(buffer, 0, buffer.Length)) > 0) {
                            waveFileWriter.WriteData(buffer, 0, read);
                        }
                    }
                }
            }
            finally {
                if (waveFileWriter != null) {
                    waveFileWriter.Dispose();
                }
            }

        }
        public AudioPlayer(Resource resource, TabPage tab)
        {
            var soundData = (Sound)resource.Blocks[BlockType.DATA];

            var stream = soundData.GetSoundStream();
            waveOut = new WaveOutEvent();

            if (soundData.Type == Sound.AudioFileType.WAV)
            {
                var rawSource = new WaveFileReader(stream);
                waveOut.Init(rawSource);
            }
            else if (soundData.Type == Sound.AudioFileType.MP3)
            {
                var rawSource = new Mp3FileReader(stream);
                waveOut.Init(rawSource);
            }

            playButton = new Button();
            playButton.Text = "Play";
            playButton.TabIndex = 1;
            playButton.Size = new Size(100, 25);
            playButton.Click += PlayButton_Click;

            tab.Controls.Add(playButton);
        }
Exemplo n.º 7
0
        public static Sound Read(Stream source)
        {
            BinaryReaderEx reader = new BinaryReaderEx(source);
            Sound result = new Sound();

            int id = reader.ReadInt32();
            if (id == 0x00394453)
            {
                int headerLength = reader.ReadInt32();
                int sampleLength = reader.ReadInt32();

                headerLength -= 12;
                if (headerLength > 0)
                    reader.ReadBytes(headerLength);

                byte[] wavData = reader.ReadBytes(sampleLength);
                using (MemoryStream wavDataMem = new MemoryStream(wavData))
                {
                    using (WaveStream wavStream = new WaveFileReader(wavDataMem))
                    {
                        byte[] rawWaveData = new byte[wavStream.Length];
                        wavStream.Read(rawWaveData, 0, (int)wavStream.Length);
                        result.SetSound(rawWaveData, wavStream.WaveFormat);
                    }
                }
            }

            return result;
        }
Exemplo n.º 8
0
        /// <summary>
        ///  Convert WAV to MP3 using libmp3lame library
        /// </summary>
        /// <param name="waveFileName">WAV filename</param>
        /// <param name="mp3FileName">MP3 filename</param>
        /// <param name="bitRate">Bit rate, default 128</param>
        /// <param name="artist">Optional artist name</param>
        /// <param name="album">Optional album name</param>
        /// <param name="setID3Tags">Set ID3 tags</param>
        public static bool WavToMP3(string waveFileName, string mp3FileName, int bitRate = 128, string artist = null, string album = null, bool setID3Tags = false, string genre = "148")
        {
            bool result = true;
            try
            {
                ID3TagData tags = new ID3TagData();
                if (setID3Tags)
                {
                    if (!String.IsNullOrEmpty(artist))
                    {
                        tags.Artist = artist;
                        tags.Album = album;
                        tags.Genre = genre;
                    }
                }

                using (var reader = new WaveFileReader(waveFileName))
                using (var writer = new LameMP3FileWriter(mp3FileName, reader.WaveFormat, bitRate, tags))
                    reader.CopyTo(writer);

            }
            catch (Exception)
            {
                result = false;
            }

            return result;
        }
Exemplo n.º 9
0
 public void playbackFile(string filename)
 {
     WaveFileReader reader = new WaveFileReader(filename);
     WaveChannel32 channelStream = new WaveChannel32(reader);
     mixer.AddInputStream(channelStream);
     channelStream.Position = 0;
 }
Exemplo n.º 10
0
        public PianoSynth()
        {
            mixer = new WaveMixerStream32();
            mixer.AutoStop = false;

            int i = 0;
            foreach (var note in noteFiles)
            {
                reader[i] = new WaveFileReader(note);

                offsetStream[i] = new WaveOffsetStream(reader[i]);
                channelSteam[i] = new WaveChannel32(offsetStream[i]);
                channelSteam[i].Position = channelSteam[i].Length;
                mixer.AddInputStream(channelSteam[i]);

                i++;
            }

            if (waveOutDevice == null)
            {
                waveOutDevice = new WaveOut {DeviceNumber = 0};
                waveOutDevice.Init(mixer);
                waveOutDevice.Volume = 0;
                waveOutDevice.Play();
                waveOutDevice.Volume = 100;
            }
        }
Exemplo n.º 11
0
 // Maethod to initialize thread for opening the wav file
 public void initPlay()
 {
     DisposeWave();
     waveReader = new NAudio.Wave.WaveFileReader(wavOpenName);
     waveOut    = new NAudio.Wave.DirectSoundOut();
     waveOut.Init(new NAudio.Wave.WaveChannel32(waveReader));
 }
Exemplo n.º 12
0
        // Method needed to cleanup outputStream and waveOut file
        private void DisposeWave()
        {
            if (sourceStream != null)
            {
                sourceStream.StopRecording();
                sourceStream.Dispose();
                sourceStream = null;
            }
            if (waveWriter != null)
            {
                waveWriter.Dispose();
                waveWriter = null;
            }

            if (waveOut != null)
            {
                if (waveOut.PlaybackState == NAudio.Wave.PlaybackState.Playing)
                {
                    waveOut.Stop();
                }
                waveOut.Dispose();
                waveOut.Stop();
                waveOut = null;
            }

            if (waveReader != null)
            {
                waveReader.Dispose();
                waveReader.Close();
                waveReader = null;
            }
        }
Exemplo n.º 13
0
        public SoundResource(ResourceManager mgr, string fullName, Stream stream, Format fmt)
        {
            _manager = mgr;
            FullName = fullName;

            switch (fmt)
            {
                case Format.MP3:
                {
                    Mp3FileReader mp3 = new Mp3FileReader(stream);
                    _reader = mp3;
                    break;
                }
                case Format.WAV:
                {
                    WaveFileReader wav = new WaveFileReader(stream);
                    _reader = wav;
                    break;
                }
                default:
                    throw new InvalidOperationException("Unsupported extension.");
            }

            _stream = new WaveChannel32(_reader);
            _stream.PadWithZeroes = false;

            _wavDevice.PlaybackStopped += _wavDevice_PlaybackStopped;
        }
Exemplo n.º 14
0
        public void OutputWaveToFile(
            string textToSpeak,
            string waveFile)
        {
            if (string.IsNullOrWhiteSpace(textToSpeak))
            {
                return;
            }

            this.StartSasara();

            var tempWave = Path.GetTempFileName();

            talker.OutputWaveToFile(
                textToSpeak,
                tempWave);

            // ささらは音量が小さめなので増幅する
            using (var reader = new WaveFileReader(tempWave))
            {
                var prov = new VolumeWaveProvider16(reader);
                prov.Volume = Settings.Default.SasaraGain;

                WaveFileWriter.CreateWaveFile(
                    waveFile,
                    prov);
            }

            if (File.Exists(tempWave))
            {
                File.Delete(tempWave);
            }
        }
Exemplo n.º 15
0
        public static Boolean SpeakerTest(int channel)
        {
            String wavFile = "";

            wavFile = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
            NAudio.Wave.WaveFileReader wave   = null;
            NAudio.Wave.DirectSoundOut output = null;

            if (channel == 0)
            {
                wavFile += "\\440Hz_sine_left.wav";
            }
            else
            {
                wavFile += "\\440Hz_sine_right.wav";
            }

            wave   = new NAudio.Wave.WaveFileReader(wavFile);
            output = new NAudio.Wave.DirectSoundOut();

            output.Init(new WaveChannel32(wave));
            output.Play();

            return(false);
        }
Exemplo n.º 16
0
 private void EncodeFile()
 {
     string inputFileName = GetInputFileName("Select PCM WAV File to Encode");
     if (inputFileName == null)
         return;
     using (var reader = new WaveFileReader(inputFileName))
     {
         if (reader.WaveFormat.Encoding != WaveFormatEncoding.Pcm)
         {
             MessageBox.Show("Please select a PCM WAV file to encode");
             return;
         }
         WaveFormat targetFormat = GetTargetFormat(reader.WaveFormat);
         if (targetFormat == null)
         {
             return;
         }
         string outputFileName = GetOutputFileName("Select Ouput File Name");
         if (outputFileName == null)
         {
             return;
         }
         using (WaveStream convertedStream = new WaveFormatConversionStream(targetFormat, reader))
         {
             WaveFileWriter.CreateWaveFile(outputFileName, convertedStream);
         }
         if (checkBoxAutoLaunchConvertedFile.Checked)
         {
             System.Diagnostics.Process.Start(outputFileName);
         }
     }
 }
Exemplo n.º 17
0
        // set everything up
        public BonIverStemPlayer(Engine.Engine engine) {
            mixer.AutoStop = false;
            waveOutDevice.Init(mixer);
            Engine = engine;

            // load in each of our files
            reader[0] = new WaveFileReader(@"C:\\Users\\Badger\\repos\\balloon\\SkeletalTracking\\boniver\\bangorkook.wav");
            reader[1] = new WaveFileReader(@"C:\Users\Badger\repos\balloon\SkeletalTracking\boniver\chippewa_falls.wav");
            reader[2] = new WaveFileReader(@"C:\Users\Badger\repos\balloon\SkeletalTracking\boniver\eleva.wav");
            reader[3] = new WaveFileReader(@"C:\Users\Badger\repos\balloon\SkeletalTracking\boniver\gilman.wav");
            reader[4] = new WaveFileReader(@"C:\Users\Badger\repos\balloon\SkeletalTracking\boniver\grand_rapids.wav");
            reader[5] = new WaveFileReader(@"C:\Users\Badger\repos\balloon\SkeletalTracking\boniver\heigh_on.wav");
            reader[6] = new WaveFileReader(@"C:\Users\Badger\repos\balloon\SkeletalTracking\boniver\lake_hallie.wav");
            reader[7] = new WaveFileReader(@"C:\Users\Badger\repos\balloon\SkeletalTracking\boniver\le_grange_wi.wav");
            reader[8] = new WaveFileReader(@"C:\Users\Badger\repos\balloon\SkeletalTracking\boniver\long_plain.wav");
            reader[9] = new WaveFileReader(@"C:\Users\Badger\repos\balloon\SkeletalTracking\boniver\mandolin_wa.wav");
            reader[10] = new WaveFileReader(@"C:\Users\Badger\repos\balloon\SkeletalTracking\boniver\virginia.wav");

            // set the starting positions
            // and load into the mixer
            for (int i = 0; i < 11; i++) {
                channelStream[i] = new WaveChannel32(reader[i]);
                channelStream[i].Position = 0;
                mixer.AddInputStream(channelStream[i]);
            }
        }
Exemplo n.º 18
0
 public void ReaderShouldReadBackSameDataWrittenWithWrite()
 {
     var ms = new MemoryStream();
     var testSequence = new byte[] { 0x1, 0x2, 0xFF, 0xFE };
     using (var writer = new WaveFileWriter(new IgnoreDisposeStream(ms), new WaveFormat(16000, 24, 1)))
     {
         writer.Write(testSequence, 0, testSequence.Length);
     }
     // check the Reader can read it
     ms.Position = 0;
     using (var reader = new WaveFileReader(ms))
     {
         Assert.AreEqual(16000, reader.WaveFormat.SampleRate, "Sample Rate");
         Assert.AreEqual(24, reader.WaveFormat.BitsPerSample, "Bits Per Sample");
         Assert.AreEqual(1, reader.WaveFormat.Channels, "Channels");
         Assert.AreEqual(testSequence.Length, reader.Length, "File Length");
         var buffer = new byte[600]; // 24 bit audio, block align is 3
         int read = reader.Read(buffer, 0, buffer.Length);
         Assert.AreEqual(testSequence.Length, read, "Data Length");
         for (int n = 0; n < read; n++)
         {
             Assert.AreEqual(testSequence[n], buffer[n], "Byte " + n);
         }
     }
 }
Exemplo n.º 19
0
 private void ConvertWavTo10SecondWavs(FileInfo inputFile)
 {
     var samplesOutWav = @"..\..\..\samples\wav10seconds\";
     using (var inAudio = new WaveFileReader(inputFile.FullName))
     {
         //Calculate required byte[] buffer.
         var buffer = new byte[10*inAudio.WaveFormat.AverageBytesPerSecond];//Assume average will be constant for WAV format.
         int index = 0;
         do
         {
             var outFile = string.Format("{0}{1}.{2:0000}.wav",
             samplesOutWav, inputFile.Name.Replace(inputFile.Extension, string.Empty), index);
             int bytesRead = 0;
             do
             {
                 bytesRead = inAudio.Read(buffer, 0, buffer.Length - bytesRead);
             } while (bytesRead > 0 && bytesRead < buffer.Length);
             //Write new file
             using (var waveWriter = new WaveFileWriter(outFile, inAudio.WaveFormat))
             {
                 waveWriter.Write(buffer, 0, buffer.Length);
             }
             index++;
         } while (inAudio.Position < inAudio.Length);
     }
 }
Exemplo n.º 20
0
        public AudioSample(string fileName)
        {
            _fileName = fileName;
            WaveFileReader reader = new WaveFileReader(fileName);
            //offsetStream = new WaveOffsetStream(reader);
            //channelStream = new WaveChannel32(offsetStream);
            channelStream = new WaveChannel32(reader);
            muted = false;
            volume = 1.0f;



            #region ReverseStuff

            //Code to reverse
            NAudioBufferReverse nbr = new NAudioBufferReverse();
            reversedSample = new byte[(int)channelStream.Length];
            channelStream.Read(reversedSample, 0, (int)channelStream.Length);
            bytesPerSample = (channelStream.WaveFormat.BitsPerSample / 8) * channelStream.WaveFormat.Channels;
            reversedSample = nbr.reverseSample(reversedSample, (int)channelStream.Length, bytesPerSample);

            #endregion


        }
Exemplo n.º 21
0
 public void FlushUpdatesHeaderEvenIfDisposeNotCalled()
 {
     var ms = new MemoryStream();
     var testSequence = new byte[] { 0x1, 0x2, 0xFF, 0xFE };
     var testSequence2 = new byte[] { 0x3, 0x4, 0x5 };
     var writer = new WaveFileWriter(new IgnoreDisposeStream(ms), new WaveFormat(16000, 24, 1));
     writer.Write(testSequence, 0, testSequence.Length);
     writer.Flush();
     // BUT NOT DISPOSED
     // another write that was not flushed
     writer.Write(testSequence2, 0, testSequence2.Length);
     
     // check the Reader can read it
     ms.Position = 0;
     using (var reader = new WaveFileReader(ms))
     {
         Assert.AreEqual(16000, reader.WaveFormat.SampleRate, "Sample Rate");
         Assert.AreEqual(24, reader.WaveFormat.BitsPerSample, "Bits Per Sample");
         Assert.AreEqual(1, reader.WaveFormat.Channels, "Channels");
         Assert.AreEqual(testSequence.Length, reader.Length, "File Length");
         var buffer = new byte[600]; // 24 bit audio, block align is 3
         int read = reader.Read(buffer, 0, buffer.Length);
         Assert.AreEqual(testSequence.Length, read, "Data Length");
         
         for (int n = 0; n < read; n++)
         {
             Assert.AreEqual(testSequence[n], buffer[n], "Byte " + n);
         }
     }
     writer.Dispose(); // to stop the finalizer from moaning
 }
Exemplo n.º 22
0
        /// <summary>
        /// Преобразует поток с wav файлом в mp3
        /// </summary>
        /// <param name="wavFile"></param>
        public static void WavToMP3(string wavPath, string Mp3path)
        {
            using (Stream source = new FileStream(wavPath, FileMode.Open))
                using (Stream Mp3file = new FileStream(Mp3path, FileMode.Create))
                    using (NAudio.Wave.WaveFileReader rdr = new NAudio.Wave.WaveFileReader(source))
                    {
                        WaveLib.WaveFormat fmt = 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   = rdr.WaveFormat.AverageBytesPerSecond;
                        byte[] buffer = new byte[blen];

                        Yeti.MMedia.Mp3.Mp3Writer mp3 = new Yeti.MMedia.Mp3.Mp3Writer(Mp3file, fmt, conf);

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

                        Mp3file.Flush();
                        mp3.Close();
                    }
        }
Exemplo n.º 23
0
        /// <summary>指定したパーセンテージで音量を増減させた新しいwavデータを生成します。</summary>
        /// <param name="wav">元のwavデータ</param>
        /// <param name="factorPercent">音量のパーセンテージ(0~200くらいを想定)</param>
        /// <returns>音量を変更したあとのwavデータ</returns>
        public static byte[] ChangeVolume(byte[] wav, int factorPercent)
        {
            var result = new byte[wav.Length];

            using (var msIn = new MemoryStream(wav))
            using (var fr = new WaveFileReader(msIn))
            using (var msOut = new MemoryStream(result))
            using (var fw = new WaveFileWriter(msOut, fr.WaveFormat))
            {
                var allVolumes = new List<float>();
                while (fr.CurrentTime < fr.TotalTime)
                {
                    var vs = fr.ReadNextSampleFrame();
                    foreach (var v in vs)
                    {
                        allVolumes.Add(v);
                    }
                }

                fw.WriteSamples(
                    allVolumes.Select(v => v * factorPercent / 100.0f).ToArray(),
                    0, 
                    allVolumes.Count
                    );
            }

            return result;
        }
Exemplo n.º 24
0
 public void CanLoadAndReadVariousProblemWavFiles()
 {
     string testDataFolder = @"C:\Users\Mark\Downloads\NAudio";
     if (!Directory.Exists(testDataFolder))
     {
         Assert.Ignore("{0} not found", testDataFolder);
     }
     foreach (string file in Directory.GetFiles(testDataFolder, "*.wav"))
     {
         string wavFile = Path.Combine(testDataFolder, file);
         Debug.WriteLine(String.Format("Opening {0}", wavFile));
         using (var reader = new WaveFileReader(wavFile))
         {
             byte[] buffer = new byte[reader.WaveFormat.AverageBytesPerSecond];
             int bytesRead;
             int total = 0;
             do
             {
                 bytesRead = reader.Read(buffer, 0, buffer.Length);
                 total += bytesRead;
             } while (bytesRead > 0);
             Debug.WriteLine(String.Format("Read {0} bytes", total));
         }
     }
 }
Exemplo n.º 25
0
        private void TrimForm_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(WavFile))
            {
                using (NAudio.Wave.WaveFileReader reader = new NAudio.Wave.WaveFileReader(WavFile)) {
                    AdvWaveViewer1.WaveStream = new NAudio.Wave.WaveFileReader(WavFile);
                    //reader.WaveFormat.SampleRate
                }

                NumericRightS.Maximum  = decimal.MaxValue;
                NumericRight.Maximum   = AdvWaveViewer1.MaxSamples;
                NumericRight.Increment = AdvWaveViewer1.SamplesPerPixel;

                NumericLeftS.Maximum  = decimal.MaxValue;
                NumericLeft.Maximum   = decimal.MaxValue;
                NumericLeft.Increment = AdvWaveViewer1.SamplesPerPixel;

                if (startpos == endpos & endpos == 0)
                {
                    NumericRight.Value = AdvWaveViewer1.MaxSamples;
                }
                else
                {
                    AdvWaveViewer1.rightpos = endpos;
                    AdvWaveViewer1.leftpos  = startpos;
                    NumericRight.Value      = AdvWaveViewer1.rightSample;
                    NumericLeft.Value       = AdvWaveViewer1.leftSample;
                }
            }
        }
Exemplo n.º 26
0
 public static double GetDurationMillisec(byte[] wav)
 {
     using (var ms = new MemoryStream(wav))
     using (var fr = new WaveFileReader(ms))
     {
         return fr.TotalTime.TotalMilliseconds;
     }
 }
Exemplo n.º 27
0
 public MixDiffStream(string fileName)
 {
     WaveFileReader reader = new WaveFileReader(fileName);
     offsetStream = new WaveOffsetStream(reader);
     channelSteam = new WaveChannel32(offsetStream);
     muted = false;
     volume = 1.0f;
 }
 public WavSoundSignalReader(string file)
 {
     _file = file;
     _reader = new WaveFileReader(file);
     SampleRate = _reader.WaveFormat.SampleRate;
     Channels = _reader.WaveFormat.Channels;
     Length = (int) (_reader.SampleCount/Channels);
 }
 public override void Reset()
 {
     if (_reader != null)
     {
         _reader.Close();
     }
     _reader = new WaveFileReader(_file);
 }
Exemplo n.º 30
0
		public void SetInputWave(string waveInputFilePath, float volume) {
			// 4 bytes per sample (32 bit)
			this.wavFileReader = new WaveFileReader(waveInputFilePath);
			this.wavStream = new WaveChannel32(this.wavFileReader);
			
			// Leave headroom for plugin processing (0.20 seems OK, any higher causes digital clipping)
			this.wavStream.Volume = volume;
		}
Exemplo n.º 31
0
 public Key(string name, string sampleFile)
 {
     this.notePitch = name;
         WaveFileReader reader = new WaveFileReader(sampleFile);
         offsetStream = new WaveOffsetStream(reader);
         channelStream = new WaveChannel32(offsetStream);
         channelStream.Position = channelStream.Length;
 }
Exemplo n.º 32
0
 private void playButton_Click(object sender, EventArgs e)
 {
     waveReader = new NAudio.Wave.WaveFileReader(outputFilePath);
     output     = new NAudio.Wave.DirectSoundOut(100);
     output.Init(new NAudio.Wave.WaveChannel32(waveReader));
     output.Play();
     playButton.Enabled = false;
 }
Exemplo n.º 33
0
 private void WaveOut_PlaybackStopped(object sender, StoppedEventArgs e)
 {
     if (sender != null) (sender as WaveOutEvent).Dispose();
     if (reader != null)
     {
         reader.Dispose();
         reader = null;
     }
 }
Exemplo n.º 34
0
        private void button3_Click_1(object sender, EventArgs e)
        {
            //waveOut

            var reader = new WaveFileReader("v.wav");
            var waveOut = new WaveOut(); // or WaveOutEvent()
            waveOut.Init(reader);
            waveOut.Play();
        }
Exemplo n.º 35
0
 private void buttonSelectFile_Click(object sender, EventArgs e)
 {
     Cleanup();
     OpenFileDialog ofd = new OpenFileDialog();
     ofd.Filter = "WAV files|*.wav";
     if (ofd.ShowDialog() == DialogResult.OK)
     {
         this.reader = new WaveFileReader(ofd.FileName);
     }
 }
Exemplo n.º 36
0
 public void WritePieceOfSomeFileWav(
     string srcFilename,
     double secondIn,
     double secondOut,
     double? speedChange = null)
 {
     using (var reader = new WaveFileReader(srcFilename)) {
         WritePieceOfSomeFile_stream(reader, secondIn, secondOut, speedChange);
     }
 }
Exemplo n.º 37
0
 private static WaveStream OpenWavStream(string fileName)
 {
     WaveStream readerStream = new WaveFileReader(fileName);
     if (readerStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm)
     {
         readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream);
         readerStream = new BlockAlignReductionStream(readerStream);
     }
     return readerStream;
 }
Exemplo n.º 38
0
        public WavPlayer(string fileName)
        {
            this._fileName = fileName;
            this._wav      = new WaveFileReader(fileName);
            _time          = Convert.ToInt32(_wav.TotalTime.TotalSeconds);

            _output = new WaveOutEvent();

            _output.Init(new WaveChannel32(_wav));
        }
Exemplo n.º 39
0
        private void repeatBtn_Click(object sender, EventArgs e)
        {
            String filename = "Class" + LoginForm.classSec + "_kidWordAudio/" + levels[curPos] + ";.wav";

            DisposeWave();

            wave   = new NAudio.Wave.WaveFileReader(filename);
            output = new NAudio.Wave.DirectSoundOut();
            output.Init(new NAudio.Wave.WaveChannel32(wave));
            output.Play();
        }
Exemplo n.º 40
0
 public SampleReader(NAudio.Wave.WaveFileReader reader)
 {
     this.waveFileReader = reader;
     this.waveFormat     = waveFileReader.WaveFormat;
     this.blockOffset    = 0;
     this.sampleSize     = Convert.ToInt16(this.waveFormat.BitsPerSample / 8);
     // Buffer length must be a "block align" multiple
     this.bufferLength = (this.bufferLength / waveFileReader.BlockAlign) * waveFileReader.BlockAlign;
     this.buffer       = new byte[this.bufferLength];
     this.sampleBlock  = new short[this.bufferLength / this.sampleSize];
 }
Exemplo n.º 41
0
        void c_valueChanged(object sender, EventArgs e)
        {
            if (discard_events)
            {
                return;
            }

            var verter = (Verter)sender;
            var ev     = verter.eventType;

            if (ev == Verter.EventType.mute)
            {
                chdev(0);
                return;
            }

            if (ev == Verter.EventType.solo)
            {
                discard_events = true;
                for (var a = 0; a < gVu.Length; a++)
                {
                    gVu[a].enabled = false;
                }

                ((Verter)sender).enabled = true;
                discard_events           = false;
                chdev(0);
                return;
            }

            if (ev == Verter.EventType.airhorn)
            {
                gPreviewOn.Checked = false;
                chdev(0);

                if (unFxTimer == null)
                {
                    unFxTimer          = new Timer();
                    unFxTimer.Interval = 3000;
                    unFxTimer.Tick    += delegate(object oa, EventArgs ob)
                    {
                        unFX();
                    };
                }
                unFX();
                fx_stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Loopstream.res.sc.wav");
                fx_wav    = new NAudio.Wave.WaveFileReader(fx_stream);
                var prov2 = new NPatch.ChannelMapperOut(fx_wav.ToSampleProvider(), new int[] { (int)verter.Tag }, src.wf.Channels);
                fx_out = new NAudio.Wave.WasapiOut(src.mm, NAudio.CoreAudioApi.AudioClientShareMode.Shared, false, 100);
                fx_out.Init(prov2);
                fx_out.Play();
                unFxTimer.Start();
            }
        }
Exemplo n.º 42
0
        public void play_sound(string file)
        {
            NAudio.Wave.DirectSoundOut waveOut = new NAudio.Wave.DirectSoundOut();

            NAudio.Wave.WaveFileReader wfr  = new NAudio.Wave.WaveFileReader(file);
            NAudio.Wave.WaveOut        wOut = new NAudio.Wave.WaveOut();
            wOut.DeviceNumber = 0;
            wOut.Init(wfr);
            wOut.Play();

            waveOut.Init(wfr);

            waveOut.Play();
        }
Exemplo n.º 43
0
 private void ConvertToMP3(string fileName)
 {
     byte[] wavFile = File.ReadAllBytes(fileName);
     using (var retMs = new MemoryStream())
         using (var ms = new MemoryStream(wavFile))
             using (var rdr = new NA.WaveFileReader(ms))
                 using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, 128))
                 {
                     rdr.CopyTo(wtr);
                     wtr.Flush();
                     File.WriteAllBytes(_outputMp3Name, retMs.ToArray());
                 }
     Thread.Sleep(10000);
 }
Exemplo n.º 44
0
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (soundOut != null)
            {
                soundOut.Stop();
                soundOut.Dispose();
                soundOut = null;
            }

            if (waveFileReader != null)
            {
                waveFileReader.Dispose();
                waveFileReader = null;
            }
        }
Exemplo n.º 45
0
        static void RecordAndPlayAudio()
        {
            Console.WriteLine("Program micro   presser une touche pour commancer l'enregistrement ");
            Console.ReadKey();

            Console.WriteLine("presser une touche pour arreter l'enregistrement");
            mciSendString("open new Type waveaudio Alias recsound", "", 0, 0);
            mciSendString("record recsound", "", 0, 0);
            Console.ReadKey();

            mciSendString("save recsound recordTemp.wav", "", 0, 0); //Fichier sauvegardé dans bin/debug
            mciSendString("close recsound ", "", 0, 0);
            Console.WriteLine("Sauvergardee ");
            Console.ReadKey();


            string FileName      = "recordTemp.wav";
            string CommandString = "open " + "\"" + FileName + "\"" + " type waveaudio alias recsound";

            mciSendString(CommandString, null, 0, 0);
            CommandString = "play recsound";
            mciSendString(CommandString, null, 0, 0);

            WaveFileReader reader = new NAudio.Wave.WaveFileReader("recordTemp.wav");

            WaveFormat newFormat = new WaveFormat(16000, 16, 1);

            WaveFormatConversionStream str = new WaveFormatConversionStream(newFormat, reader);

            try
            {
                WaveFileWriter.CreateWaveFile("record.wav", str);
                Console.WriteLine("Audio converted to 16Khz");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                str.Close();
            }



            Console.ReadKey();
        }
Exemplo n.º 46
0
 private void DisposeWave()
 {
     if (output != null)
     {
         if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
         {
             output.Stop();
         }
         output.Dispose();
         output = null;
     }
     if (wave != null)
     {
         wave.Dispose();
         wave = null;
     }
 }
Exemplo n.º 47
0
 public void DisposeWave()
 {
     if (_output != null)
     {
         if (_output.PlaybackState == NAudio.Wave.PlaybackState.Playing ||
             _output.PlaybackState == NAudio.Wave.PlaybackState.Paused)
         {
             _output.Stop();
         }
         _output.Dispose();
         _output = null;
     }
     if (_wav != null)
     {
         _wav.Dispose();
         _wav = null;
     }
 }
Exemplo n.º 48
0
        /// <summary>
        /// 获取文件长度
        /// </summary>
        /// <param name="musicFilePath"></param>
        /// <returns></returns>
        public static double TotalSeconds(Stream ms)//musicFilePath是歌曲文件地址
        {
            try
            {
                using (var rdr = new NAudio.Wave.WaveFileReader(ms))
                {
                    using (var wavStream = WaveFormatConversionStream.CreatePcmStream(rdr))
                    {

                        return wavStream.TotalTime.TotalSeconds;
                    }
                }                
            }
            catch
            {
                return 0.0;
            }
        }
Exemplo n.º 49
0
        /// <summary>
        /// play sound
        /// </summary>
        /// <param name="deviceNumber">device to play on. 0  == defulet</param>
        /// <param name="path">path to file</param>
        public void playSound(int deviceNumber, byte number)
        {
            try
            {
                this.disposeWave();

                string path = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\HotKey\\sounder\\Sound" + number + ".wav";

                var waveReader = new NAudio.Wave.WaveFileReader(path);
                var waveOut    = new NAudio.Wave.WaveOut();
                waveOut.DeviceNumber = deviceNumber;
                output = waveOut;
                output.Init(waveReader);
                output.Play();
            }
            catch
            { }
        }
Exemplo n.º 50
0
        //Plays the concatenated phonics words, this is for teacher's to test if it sounds good or not !
        private void testWordBtn_Click(object sender, EventArgs e)
        {
            if (wordLabel.Text.Length > 0)
            {
                String word     = wordLabel.Text;
                String filename = @"PhonicsWord_Audio\" + word + ".wav";
                DisposeWave();

                wave   = new NAudio.Wave.WaveFileReader(filename);
                output = new NAudio.Wave.DirectSoundOut();
                output.Init(new NAudio.Wave.WaveChannel32(wave));
                output.Play();
            }
            else
            {
                MessageBox.Show("Word isn't created yet !");
            }
        }
Exemplo n.º 51
0
        public void SettimeAudio(int t)
        {
            NAudio.Wave.WaveFileReader temp = _wav;
            //  temp.CurrentTime  = temp.CurrentTime.Add( TimeSpan.FromSeconds(t * time /100000));
            // if(output.PlaybackState ==NAudio.Wave.PlaybackState.Playing)
            //         output.Stop();
            double tt = t * _time / 100000;

            if (_output != null)
            {
                _output.Stop();
            }
            _output       = new WaveOutEvent();
            _wav.Position = (long)(tt * _wav.WaveFormat.AverageBytesPerSecond);

            _output.Init(new WaveChannel32(_wav));
            _output.Play();
            Console.WriteLine("had play");
        }
Exemplo n.º 52
0
        // Простой обработчик данных - просто берет и проигрывает.
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var ofd = new OpenFileDialog();

            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".wav";
            dlg.Filter     = "WAV files (.wav)|*.wav";
            Nullable <bool> result = dlg.ShowDialog();

            if (dlg.ShowDialog() == false)
            {
                return;
            }


            wave   = new NAudio.Wave.WaveFileReader(dlg.FileName);
            output = new NAudio.Wave.DirectSoundOut();
            output.Init(new NAudio.Wave.WaveChannel32(wave));
            output.Play();
        }
Exemplo n.º 53
0
    private IEnumerator ImportAudioNAudioRoutine(string url)
    {
        var loader = new WWW(url);

        while (!loader.isDone)
        {
            yield return(loader);
        }

        Debug.Log("NAudio file play");

        NAudio.Wave.WaveOut        waveOut   = new NAudio.Wave.WaveOut();
        NAudio.Wave.WaveFileReader wavReader = new NAudio.Wave.WaveFileReader("bardintro.wav");
        Debug.Log("Format : " + wavReader.WaveFormat.ToString() + "sample count : " + wavReader.SampleCount + " :: " + wavReader.Length);


        var pcmLength = (int)wavReader.Length;
        var buffer    = new byte[pcmLength];
        var bytesRead = wavReader.Read(buffer, 0, pcmLength);

        using (FileStream fs = File.Open("generatedaudiofile", FileMode.Create))
        {
            StreamWriter sw = new StreamWriter(fs);

            int i = 0;
            for (i = 0; i < buffer.Length; i += 3)
            {
                short int16 = (short)(((buffer[i] & 0xFF) << 8) | (buffer[i + 1] & 0xFF));
                float f     = int16;
                sw.WriteLine(f);
            }
        }

        //waveOut.Play();
        yield return(new WaitForSeconds(3));

        //waveOut.Stop();
        wavReader.Dispose();
        waveOut.Dispose();
    }
Exemplo n.º 54
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            seconds = seconds - 1;
            if (seconds == 0)
            {
                clearPanel();
                stopProcess();
                gameOverLabel.Visible = true;
                restartLabel.Visible  = true;
                gameOverLabel.Text    = "GAME OVER !";
                restartLabel.Text     = "PRESS RESTART\nTO TRY AGAIN !";
                soundPicBox.Visible   = false;

                String file = @"C:\Pres_Proto\V2\MetroFrameworkDLLExample\airhorn.wav";
                wave   = new NAudio.Wave.WaveFileReader(file);
                output = new NAudio.Wave.DirectSoundOut();
                output.Init(new NAudio.Wave.WaveChannel32(wave));
                output.Play();

                MessageBox.Show("TIME'S UP !");
                MessageBox.Show("Total score: " + points);
            }
            timerLabel.Text = Convert.ToString(seconds);
        }
Exemplo n.º 55
0
        //[Test]
        public void EvaluateAudioTrigger_BasicShouldReturnTrue()
        {
            var path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Replace("file:\\", "");

            //System.IO.FileStream WaveFile = System.IO.File.OpenRead(path + "\\Data\\TestAudio.wav");
            //byte[] data = new byte[WaveFile.Length];
            int sampleRate;
            //double[] fileData = Functions.WaveFileDataPrepare(path + "\\Data\\TestAudio.wav", out sampleRate);''

            List <double> fftData = new List <double>();

            int        BUFFERSIZE     = (int)Math.Pow(2, 11);  // must be a multiple of 2
            WaveStream waveStream     = new NAudio.Wave.WaveFileReader(path + "\\Data\\TestAudio.wav");
            int        bytesPerSample = (waveStream.WaveFormat.BitsPerSample / 8) * waveStream.WaveFormat.Channels;
            int        bytesRead      = 0;

            BufferedWaveProvider bwp = new BufferedWaveProvider(new WaveFormat(44100, 1));

            bwp.BufferLength            = BUFFERSIZE * 2;
            bwp.DiscardOnBufferOverflow = true;

            byte[] waveData = new byte[BUFFERSIZE * 2];
            bytesRead = waveStream.Read(waveData, 0, 128 * bytesPerSample);
            bwp.AddSamples(waveData, 0, bytesRead);

            int frameSize = BUFFERSIZE;

            byte[] frames = new byte[frameSize];
            bwp.Read(frames, 0, frameSize);

            var waveFormEventArgs = AudioFunctions.PrepareAudioData(frames, frameSize);

            fftData.AddRange(waveFormEventArgs.FastFourierTransform);

            while (bytesRead != 0)
            {
                bytesRead = waveStream.Read(waveData, bytesRead, 128 * bytesPerSample);
                bwp.AddSamples(waveData, 0, bytesRead);

                frameSize = BUFFERSIZE;
                frames    = new byte[frameSize];
                bwp.Read(frames, 0, frameSize);

                waveFormEventArgs = AudioFunctions.PrepareAudioData(frames, frameSize);
                fftData.AddRange(waveFormEventArgs.FastFourierTransform);
            }



            //WavFile wavFile = new WavFile();
            //wavFile.ReadWav(path + "\\Data\\TestAudio.wav");

            //WaveFileReader reader = new WaveFileReader(path + "\\Data\\TestAudio.wav");
            //List<byte> testAudio1; // = File.ReadAllBytes(path + "\\Data\\TestAudio.wav").ToList();
            //int BUFFERSIZE = (int)Math.Pow(2, 14); // must be a multiple of 2

            //using (var reader = new AudioFileReader(path + "\\Data\\TestAudio.wav"))
            //{
            //	// find the max peak
            //	byte[] buffer = new byte[BUFFERSIZE];
            //	int read;
            //	do
            //	{
            //		read = reader.Read(buffer, 0, buffer.Length);
            //	} while (read > 0);

            //	testAudio1 = new List<byte>(buffer);
            //}

            Logger log = new LoggerConfiguration()
                         .MinimumLevel.Error()
                         .CreateLogger();

            var audioEvaluator = new AudioEvaluator(log);

            //if (testAudio1.Count() % 2 != 0)
            //{
            //	testAudio1.RemoveAt(testAudio1.Count() - 1);
            //}

            var trigger = new Trigger();

            trigger.Frequency1 = 645.7;
            trigger.Frequency2 = 716.10;
            trigger.Count      = 2;
            trigger.Time1      = 1;

            //wavFile.FFT(false);

            //var fftData = Functions.FFT(fileData);
            //var fftData = wavFile._aSamples;
            //var result = audioEvaluator.EvaluateAudioTrigger(trigger, fftData.ToArray());

            //result.Should().BeTrue();
        }
Exemplo n.º 56
0
        public async Task Play(ICommandContext Context, [Remainder] string youtubevid = null)
        {
            try
            {
                if (string.IsNullOrEmpty(youtubevid) && IsPlaying)
                {
                    await Context.Channel.SendMessageAsync("You did not specify a link or search.");

                    return;
                }
                if (string.IsNullOrEmpty(youtubevid) && !IsPlaying && Queue.Count == 0)
                {
                    await Context.Channel.SendMessageAsync("You did not specify a link or search.");

                    return;
                }
                if (IsPlaying && !string.IsNullOrEmpty(youtubevid))
                {
                    TimeSpan     dur     = TimeSpan.Zero;
                    string       thm     = "";
                    string       message = "";
                    YouTubeVideo v       = uvid(youtubevid, @"queue", out thm, out dur, out message);
                    if (v == null)
                    {
                        await Context.Channel.SendMessageAsync("Hmm, that didn't work. info: " + message);

                        return;
                    }
                    MusicQueueItem item = new MusicQueueItem(v, @"queue\" + v.FullName, dur, thm);
                    Queue.Enqueue(item);
                    EmbedBuilder qvidinfo = new EmbedBuilder();
                    qvidinfo.WithAuthor("Added to Queue!");
                    qvidinfo.AddField(v.Title, dur);
                    qvidinfo.ImageUrl = thm;
                    await Context.Channel.SendMessageAsync("", false, qvidinfo);

                    return;
                }
                if (!IsPlaying && !string.IsNullOrEmpty(youtubevid))//You will f*****g obey me this time;;
                {
                    TimeSpan     dur     = TimeSpan.Zero;
                    string       thm     = "";
                    string       message = "";
                    YouTubeVideo v       = uvid(youtubevid, @"queue", out thm, out dur, out message);
                    if (v == null)
                    {
                        await Context.Channel.SendMessageAsync("Hmm, that didn't work. info: " + message);

                        return;
                    }
                    MusicQueueItem item = new MusicQueueItem(v, @"queue" + v.FullName, dur, thm);
                    Queue.Enqueue(item);
                    if (Queue.Count == 1)
                    {
                        await Context.Channel.SendMessageAsync("Added to queue, but wait, Only one song. Let's play it now.");
                    }
                }
                var vidinfo = Queue.Dequeue();

                string source = @"queue";
                var    vide   = vidinfo.video;
                byte[] b      = vidinfo.video.GetBytes();
                System.IO.File.WriteAllBytes(System.IO.Path.GetFullPath(source) + "\\" + vide.FullName, b);

                var inputFile = new MediaFile {
                    Filename = source + "\\" + vide.FullName
                };
                var outputFile = new MediaFile {
                    Filename = $"{source + "\\" + vide.FullName}.wav"
                };

                using (var engine = new Engine())
                {
                    engine.GetMetadata(inputFile);

                    engine.Convert(inputFile, outputFile);
                }
                NowPlayingInfo = new EmbedBuilder();
                NowPlayingInfo.WithAuthor("Now Playing", Context.Client.CurrentUser.GetAvatarUrl(ImageFormat.Auto));
                NowPlayingInfo.AddField(vide.Title, vidinfo.duration);
                NowPlayingInfo.AddField("Voice Channel", "`" + (await Context.Guild.GetVoiceChannelAsync(ChannelID)).Name + "`");
                NowPlayingInfo.ImageUrl = vidinfo.ThumbnailURL;
                NowPlayingInfo.Color    = Color.Purple;

                await Context.Channel.SendMessageAsync("", false, NowPlayingInfo.Build());

                using (var output = new NAudio.Wave.WaveFileReader(outputFile.Filename))
                {
                    using (var ms = new System.IO.MemoryStream())
                    {
                        using (var PlayingStream = aclient.CreatePCMStream(AudioApplication.Mixed, null, 150, 0))
                        {
                            using (var resampledAudio = new MediaFoundationResampler(output, new WaveFormat(48000, 16, 2)))
                            {
                                resampledAudio.ResamplerQuality = 50;
                                WaveFileWriter.WriteWavFileToStream(ms, resampledAudio);
                                using (var cvt = new NAudio.Wave.RawSourceWaveStream(ms, new WaveFormat(48000, 2)))
                                {
                                    IsPlaying = true;//stupid f**k
                                    while (true)
                                    {
                                        if (paused)
                                        {
                                            await Task.Delay(20);

                                            continue;
                                        }

                                        byte[] buffer = new byte[81920];
                                        int    r      = await cvt.ReadAsync(buffer, 0, buffer.Length);

                                        await PlayingStream.WriteAsync(buffer, 0, r);

                                        if (Skipped)
                                        {
                                            Skipped = false;
                                            break;
                                        }
                                        //await PlayingStream.FlushAsync(new CancellationToken(paused));
                                        if (r == 0)
                                        {
                                            break;
                                        }
                                    }
                                    await PlayingStream.FlushAsync();
                                }
                            }
                        }
                    }
                }
                IsPlaying = false;//stupid f**k
                LogMessage log = new LogMessage(LogSeverity.Info, "VoiceMOD", "End of Stream. Off to next one");
                Console.WriteLine(log);

                while (Queue.Count >= 1)
                {
                    if (Queue.Count == 0)
                    {
                        break;
                    }
                    //System.Threading.SpinWait.SpinUntil(Stopped.);//wait until it is stopped for sure before calling the next play loop.


                    if (IsPlaying)
                    {
                        await Task.Delay(20);

                        continue;
                    }

                    await Play(Context);
                }
            }
            catch (Exception ex)
            {
                await Context.Channel.SendMessageAsync(ex.Message);

                Console.WriteLine(ex.ToString());
            }
        }
Exemplo n.º 57
0
        private void button6_Click(object sender, EventArgs e)

        {
            textBox2.Text = null;
            Dictionary <String, char> morse2 = new Dictionary <String, char>()
            {
                { ".-", 'A' },
                { ".-.-", 'Ą' },
                { "-...", 'B' },
                { "-.-.", 'C' },
                { "-.-..", 'Ć' },
                { "-..", 'D' },
                { ".", 'E' },
                { "..-..", 'Ę' },
                { "..-.", 'F' },
                { "--.", 'G' },
                { "....", 'H' },
                { "..", 'I' },
                { ".---", 'J' },
                { "-.-", 'K' },
                { ".-..", 'L' },
                { ".-..-", 'Ł' },
                { "--", 'M' },
                { "-.", 'N' },
                { "--.--", 'Ń' },
                { "---", 'O' },
                { "---.", 'Ó' },
                { ".--.", 'P' },
                { "--.-", 'Q' },
                { ".-.", 'R' },
                { "...", 'S' },
                { "...-...", 'Ś' },
                { "-", 'T' },
                { "..-", 'U' },
                { "...-", 'V' },
                { ".--", 'W' },
                { "-..-", 'X' },
                { "-.--", 'Y' },
                { "--..", 'Z' },
                { "--..-.", 'Ż' },
                { "--..-", 'Ź' },
                { "-----", '0' },
                { ".----", '1' },
                { "..---", '2' },
                { "...--", '3' },
                { "....-", '4' },
                { ".....", '5' },
                { "-....", '6' },
                { "--...", '7' },
                { "---..", '8' },
                { "----.", '9' },
            };
            OpenFileDialog open = new OpenFileDialog();

            open.Filter = "Wave File (*.wav)|*.wav;";
            if (open.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            DisposeWave();
            wave = new NAudio.Wave.WaveFileReader(open.FileName);
            customWaveViewer1.WaveStream = new NAudio.Wave.WaveFileReader(open.FileName);
            AudioFileReader readertest = new AudioFileReader(open.FileName);

            customWaveViewer1.Visible = true;
            label4.Visible            = true;
            int bytesnumber = (int)readertest.Length;
            var buffer      = new float[bytesnumber];

            readertest.Read(buffer, 0, bytesnumber);
            String xxx          = null;
            String odszyfrowane = null;
            int    i            = 0;
            int    poczatekbipa = 0;
            int    koniecbipa   = 0;

            while (i < buffer.Length - 1)
            {
                while (buffer[i] < 0.2 && buffer[i] > -0.2 && i < buffer.Length - 1)
                {
                    i++;
                }
                poczatekbipa = i;
                while (buffer[i] != 0 && i < buffer.Length - 1)
                {
                    i++;
                }
                if (poczatekbipa - koniecbipa > 176500 && poczatekbipa - koniecbipa < 530000 && koniecbipa != 0)
                {
                    odszyfrowane = odszyfrowane + '/';
                }
                if (poczatekbipa - koniecbipa > 530000)
                {
                    odszyfrowane = odszyfrowane + "//";
                }

                koniecbipa = i;
                if (koniecbipa - poczatekbipa > 21180)
                {
                    Console.WriteLine("Poczatek: " + poczatekbipa + " Koniec:" + koniecbipa);
                    int dlugoscbipa = koniecbipa - poczatekbipa;
                    Console.WriteLine("Długość bipa w probkach= " + dlugoscbipa);
                    int dlugoscbipawsek = dlugoscbipa / 353;
                    Console.WriteLine("Długość bipa w sekundach= " + dlugoscbipawsek);
                    if (dlugoscbipawsek < 130)
                    {
                        Console.WriteLine("Bip krótki ");
                        odszyfrowane = odszyfrowane + '.';
                    }
                    else
                    {
                        Console.WriteLine("Bip długi");
                        odszyfrowane = odszyfrowane + '-';
                    }
                }
            }
            Console.Write("Odszyfrowana zawartosc to: " + odszyfrowane);
            char[] tablica2 = null;
            tablica2 = odszyfrowane.ToCharArray();
            Console.WriteLine();
            string slowo = null;
            string odszyfrowanawiadomosc = null;

            for (int x = 0; x < odszyfrowane.Length; x++)
            {
                if (tablica2[x] != '/')
                {
                    slowo = slowo + tablica2[x];
                }
                else
                {
                    if (slowo == null)
                    {
                        odszyfrowanawiadomosc = odszyfrowanawiadomosc + ' ';
                    }
                    else if (morse2.ContainsKey(slowo))
                    {
                        odszyfrowanawiadomosc = odszyfrowanawiadomosc + morse2[slowo];
                    }
                    slowo = null;
                }
            }
            textBox3.Text = odszyfrowanawiadomosc;
            Console.WriteLine("Odszyfrowana wiadomość to: " + odszyfrowanawiadomosc);
            MessageBox.Show(Convert.ToString(buffer.Length));
            output = new NAudio.Wave.DirectSoundOut();
            output.Init(new NAudio.Wave.WaveChannel32(wave));
            output.Play();
        }
Exemplo n.º 58
0
        /// <summary>
        /// Creates an audio source from a WAV file (16bit PCM 16kHz - 320 bytes / 10ms).
        /// </summary>
        /// <param name="path">Path of the audio file.</param>
        /// <param name="dataOnly">True to emit only the "data" section. False to emit the entire WAV file content.</param>
        public WavFileAudioSource(string path, bool dataOnly)
        {
            this.SourceFile = path;
            this.data       = File.ReadAllBytes(this.SourceFile);
            bool needsConversion = false;


            if (Path.GetExtension(path).ToLowerInvariant() != ".wav")
            {
                needsConversion = true;
            }
            else
            {
                using (NAudio.Wave.WaveFileReader testReader = new NAudio.Wave.WaveFileReader(path))
                {
                    int sampleRate    = testReader.WaveFormat.SampleRate;
                    int bitsPerSample = testReader.WaveFormat.BitsPerSample;
                    int numChannels   = testReader.WaveFormat.Channels;
                    if (sampleRate != 16000 || bitsPerSample != 16 || numChannels != 1)
                    {
                        needsConversion = true;
                    }
                }
            }
            if (needsConversion)
            {
                WaveFormat desiredFormat = new WaveFormat(16000, 16, 1);
                string     tempFile      = Path.GetTempFileName();
                //Needs conversion
                using (var reader = new MediaFoundationReader(path))
                    using (var resampler = new MediaFoundationResampler(reader, desiredFormat))
                    {
                        WaveFileWriter.CreateWaveFile(tempFile, resampler);
                        this.SourceFile = tempFile;
                        this.data       = File.ReadAllBytes(this.SourceFile);
                    }
                using (WaveFileReader r = new WaveFileReader(tempFile))
                {
                    Duration = r.TotalTime;
                }

                File.Delete(tempFile);
            }
            else
            {
                using (WaveFileReader r = new WaveFileReader(path))
                {
                    Duration = r.TotalTime;
                }
            }


            if (dataOnly)
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    // WAV HEADER
                    //  chunk type "RIFF" (0x52494646)
                    //  RIFF type "WAVE" (0x57415645)
                    int chunkType = BitConverter.ToInt32(this.data, 0);
                    if (chunkType != 0x46464952)
                    {
                        throw new InvalidDataException("Invalid WAV file");
                    }
                    UInt32 size     = BitConverter.ToUInt32(this.data, 4);
                    int    riffType = BitConverter.ToInt32(this.data, 8);
                    if (riffType != 0x45564157)
                    {
                        throw new InvalidDataException("Invalid WAV file");
                    }
                    // Read WAV chunks
                    int chunkStartIndex = 12;
                    while (chunkStartIndex < (size - 8))
                    {
                        chunkType = BitConverter.ToInt32(this.data, chunkStartIndex);
                        char[] ct        = ASCIIEncoding.ASCII.GetChars(this.data, chunkStartIndex, 4);
                        int    chunkSize = (int)BitConverter.ToUInt32(this.data, chunkStartIndex + 4);
                        // chunk type "data" (0x61746164)
                        if (chunkType == 0x61746164)
                        {
                            stream.Write(this.data, chunkStartIndex + 8, chunkSize - 8);
                        }
                        chunkStartIndex += 8 + chunkSize;
                    }
                    this.data = stream.ToArray();
                }
            }
        }
Exemplo n.º 59
0
    /// <summary>
    /// Build all the temp files
    /// </summary>
    /// <remarks>
    /// One of the most hideous functions ever written.  Refactoring would be nice.
    /// </remarks>
    public void CreateTempFiles()
    {
        /* Dev links:
         *
         * http://localhost:82/player/epgcbha - clerks mp3 - id46
         *
         * http://localhost:82/player/dpccbha - beavis wav - id32
         *
         * http://localhost:82/player/dpbcbha - ace losers mp3 - id31
         *
         * http://192.168.1.117:82/player/fqavbha - borat wav - id50 - it is nice - won't convert to mp3
         *
         */


        dynamic theSound     = null;
        Stream  outputStream = new MemoryStream();

        if (_requestInfo.IsValid)   // Functions.IsNumeric(soundId))
        {
            int soundId = _requestInfo.SoundId;

            //
            // First, look in the cache and see if we have a converted mp3 there already
            //
            string targetMp3File = LocalMp3File;    //Functions.CombineElementsWithDelimiter("\\", _targetPath, string.Format("id{0}.mp3", soundId));
            string targetWavFile = LocalWavFile;    // Functions.CombineElementsWithDelimiter("\\", _targetPath, string.Format("id{0}.wav", soundId));

            //if (!NeedToCreateAtLeastOneFile(targetMp3File, targetWavFile))
            if (HaveAtLeastOneFile(targetMp3File, targetWavFile))
            {
                return;
            }
            else
            {
                //
                // OK, let's grab the sound data from the DB
                //
                theSound = GetSoundData(Functions.ConvertInt(soundId, -1));

                if (theSound != null && theSound.Id >= 0)
                {
                    //
                    // The DB returns HTML-ready bytes.  It would be more efficient to return the binary data.  Then we wouldn't have to do 2 conversions.
                    // Todo!
                    //
                    byte[] originalSourceByteArray = System.Convert.FromBase64String(theSound.Data);

                    if (Functions.IsWav(theSound.FileName))
                    {
                        bool successfulWavConversionToMp3 = false;

                        //
                        // It's an wav, convert to mp3
                        //
                        Mp3Writer outputMp3Writer = null;
                        // Mp3Writer outputFileMp3Writer = null;

                        //
                        // These are WaveLib.WaveStream objects that wrap the LAME thing
                        //
                        WaveStream waveDataToConvertToMp3    = null;
                        WaveStream convertedSourceWaveStream = null;
                        WaveStream originalSourceWaveStream  = new WaveStream(new MemoryStream(originalSourceByteArray));

                        try
                        {
                            outputMp3Writer        = new Mp3Writer(outputStream, originalSourceWaveStream.Format);
                            waveDataToConvertToMp3 = originalSourceWaveStream;
                        }
                        catch         // (Exception ex)
                        {
                            outputMp3Writer = null;

                            //
                            // The source WAV isn't compatible with the LAME thingy.  Let's try to convert it to something we know is usable with the NAudio thingy.
                            // Then we'll use the NAudio stuff to try to get the LAME stuff to work.
                            //
                            //MemoryStream tempMemStream = new MemoryStream();
                            int sampleRate = 16000;
                            int bitDepth   = 16;

                            //
                            // Note: there appears to be a bug in the LAME thing for files with 1 channel (mono).  The file plays at double speed.
                            //
                            int channels = 2;
                            NAudio.Wave.WaveFormat targetFormat = new NAudio.Wave.WaveFormat(sampleRate, bitDepth, channels);

                            NAudio.Wave.WaveStream stream = new NAudio.Wave.WaveFileReader(new MemoryStream(originalSourceByteArray));
                            NAudio.Wave.WaveFormatConversionStream str = null;

                            try
                            {
                                str = new NAudio.Wave.WaveFormatConversionStream(targetFormat, stream);
                            }
                            catch (Exception ex3)
                            {
                                //
                                // The borat "It is nice" WAV won't convert, has strange exception.  Todo: add logging and fix.
                                //
                                ErrorMsg = string.Format("Well, naudio can't convert the WAV to the target WAV format either: {0}", ex3.Message);
                            }

                            if (str != null)
                            {
                                //
                                // For lack of a better solution to get the bytes from the converted data into a "WaveStream" variable, use these
                                // available methods to write to a disk file and then open up the disk file.  The problem with directly converting
                                // with memory streams is that the required headers (like "RIFF") aren't written into the converted stream at this point.
                                //
                                NAudio.Wave.WaveFileWriter.CreateWaveFile(targetWavFile, str);
                                convertedSourceWaveStream = new WaveStream(targetWavFile);

                                //
                                // Now we have a correct WAV memory stream
                                //
                                try
                                {
                                    WaveFormat format = convertedSourceWaveStream.Format;
                                    outputMp3Writer        = new Mp3Writer(outputStream, format);
                                    waveDataToConvertToMp3 = convertedSourceWaveStream;
                                }
                                catch (Exception ex2)
                                {
                                    //
                                    // Crap, I think we're hosed
                                    //
                                    ErrorMsg = string.Format("Oops - second try - can't process this file: {0}", ex2.Message);
                                }
                            }
                        }


                        if (outputMp3Writer != null)
                        {
                            //
                            // If we're here, we've successfully created the MP3 converter from the WAV file, and our data stream
                            // is in the variable "waveDataToConvertToMp3"
                            //
                            try
                            {
                                byte[] buff = new byte[outputMp3Writer.OptimalBufferSize];
                                int    read = 0;
                                while ((read = waveDataToConvertToMp3.Read(buff, 0, buff.Length)) > 0)
                                {
                                    outputMp3Writer.Write(buff, 0, read);
                                }

                                //
                                // We have mp3 bytes, write 'em
                                //
                                // FileStream outputMp3File = new FileStream(targetMp3File, FileMode.CreateNew);
                                //outputMp3File.Write(originalSourceByteArray, 0, originalSourceByteArray.Length);
                                using (Stream outputMp3File = File.OpenWrite(targetMp3File))
                                {
                                    outputStream.Position = 0;
                                    Functions.CopyStream(outputStream, outputMp3File);
                                }

                                successfulWavConversionToMp3 = true;
                            }
                            catch (Exception ex)
                            {
                                ErrorMsg = string.Format("Oops, fatal error: {0}", ex.Message);
                            }
                            finally
                            {
                                outputMp3Writer.Close();
                                waveDataToConvertToMp3.Close();
                            }
                        }

                        if (!successfulWavConversionToMp3)
                        {
                            //
                            // Well, everthing failed.  We have a WAV at least, let's go ahead and write that.
                            //
                            File.WriteAllBytes(targetWavFile, originalSourceByteArray);
                        }

                        //
                        // Let's clean this stuff up
                        //
                        originalSourceWaveStream.Close();

                        if (convertedSourceWaveStream != null)
                        {
                            convertedSourceWaveStream.Close();
                        }
                    }
                    else
                    {
                        FileStream outputMp3File = null;
                        try
                        {
                            outputMp3File = new FileStream(targetMp3File, FileMode.CreateNew);
                            //
                            // We have mp3 bytes, write 'em
                            //
                            outputMp3File.Write(originalSourceByteArray, 0, originalSourceByteArray.Length);
                        }
                        catch
                        {
                            // Maybe we have the file already by another thread?
                            ErrorMsg = "Have mp3, can't write to disk.";
                        }
                        finally
                        {
                            if (outputMp3File != null)
                            {
                                outputMp3File.Close();
                            }
                        }

                        /*
                         * Huge todo: this code works fine on Windows 7, but doesn't work on Windows 2008 Server.  The problem is two fold:
                         *
                         *  a) The two mp3 encoders installed by Win7 (l3codeca.acm and l3codecp.acm) don't exist.  I see no way to "install" them.
                         *      This site comes closes to explaining, but these reg keys do NOT exist so the solution doesn't work:
                         *      http://blog.komeil.com/2008/06/enabling-fraunhofer-mp3-codec-vista.html
                         *
                         *  b) The alternate option explained here:
                         *      http://stackoverflow.com/questions/5652388/naudio-error-nodriver-calling-acmformatsuggest/5659266#5659266
                         *      Also doesn't work since the COM object for the DMO isn't registered on Win2K8.  The Windows SDK is supposed to have it,
                         *      but it doesn't install properly on the server.  Also Win Media Player won't install with a weird "There is no update to Windows Media Player".
                         *
                         *  I've googled for a long time, but this is a tricky one.  Maybe Microsoft needs to be contacted?
                         *
                         * This is required to create WAV files for Firefox to play.  Otherwise you have to click on a link. (alt solution: embed?)
                         *
                         *                      NAudio.Wave.Mp3FileReader reader = null;
                         *                      try
                         *                      {
                         *                              //
                         *                              // Let's write the WAV bytes
                         *                              // http://hintdesk.com/c-mp3wav-converter-with-lamenaudio/
                         *                              //
                         *                              using (reader = new NAudio.Wave.Mp3FileReader(targetMp3File))
                         *                              {
                         *                                      using (NAudio.Wave.WaveStream pcmStream = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(reader))
                         *                                      {
                         *                                              NAudio.Wave.WaveFileWriter.CreateWaveFile(targetWavFile, pcmStream);
                         *                                      }
                         *                              }
                         *                      }
                         *                      catch
                         *                      {
                         *                              ErrorMsg = "Have mp3, can't convert to WAV";
                         *                      }
                         *                      finally
                         *                      {
                         *                              if (reader != null)
                         *                              {
                         *                                      reader.Close();
                         *                              }
                         *                      }
                         *
                         */
                    }
                }
                else
                {
                    ErrorMsg = "Cannot get sound id";
                }
            }
        }
        else
        {
            ErrorMsg = string.Format("Invalid request parameter: {0}", _encryptedPlayerRequest);
        }
    }