Beispiel #1
0
        /// <summary>
        /// Resample source into 16 bit WAV mono output with the target sampling rate.
        /// Output stream includes modified RIFF header.
        /// </summary>
        /// <param name="sourceStream"></param>
        /// <param name="targetSampleRate"></param>
        /// <param name="targetChannels"></param>
        /// <returns></returns>
        public static MemoryStream Resample(MemoryStream sourceStream, int targetSampleRate)
        {
            /*Read from the wav file's contents using stream */
            using (var inputReader = new WaveFileReader(sourceStream))
            {
                int sourceChannels = inputReader.WaveFormat.Channels;

                WdlResamplingSampleProvider resampler;

                /*Stereo source. Must convert to mono with StereoToMonoSampleProvider */
                if (sourceChannels == 2)
                {
                    var monoSampleProvider = new StereoToMonoSampleProvider(inputReader.ToSampleProvider());
                    resampler = new WdlResamplingSampleProvider(monoSampleProvider, targetSampleRate);
                }
                else
                {
                    resampler = new WdlResamplingSampleProvider(inputReader.ToSampleProvider(), targetSampleRate);
                }

                MemoryStream outStream = new MemoryStream();

                /*Ensure that header has correct RIFF format with data appended after header.*/
                WaveFileWriter.WriteWavFileToStream(outStream, resampler.ToWaveProvider16());

                outStream.Position = 0;

                return(outStream);
            }
        }
Beispiel #2
0
        internal ISampleProvider SupplyDoublePad(DoublePadVelocityType velocity, WaveFileReader file)
        {
            TimeSpan totalTimeSpan;

            totalTimeSpan = file.TotalTime; //get length of audio file

            //adjust starting point of file accordingly
            if (velocity.Equals(DoublePadVelocityType.High))
            {
                return(file.ToSampleProvider());
            }
            else if (velocity.Equals(DoublePadVelocityType.Middle))
            {
                TimeSpan timeSpan = new TimeSpan(0, 0, (int)(totalTimeSpan.TotalSeconds * 0.70));
                return(file.ToSampleProvider().Skip(timeSpan));
            }
            else if (velocity.Equals(DoublePadVelocityType.Low))
            {
                TimeSpan timeSpan = new TimeSpan(0, 0, (int)(totalTimeSpan.TotalSeconds * 0.40));
                return(file.ToSampleProvider().Skip(timeSpan));
            }
            else
            {
                return(null);
            }
        }
        public SampleBuffer(string filename, Channel.Sides side)
        {
            _reader    = new WaveFileReader(filename);
            Count      = (int)_reader.SampleCount;
            SampleRate = _reader.WaveFormat.SampleRate;
            Length     = TimeSpan.FromSeconds((double)Count / SampleRate);
            switch (side)
            {
            case Channel.Sides.Left:
                _sampleProvider = _reader.ToSampleProvider().ToMono(1.0f, 0.0f);
                break;

            case Channel.Sides.Right:
                _sampleProvider = _reader.ToSampleProvider().ToMono(0.0f, 1.0f);
                break;

            case Channel.Sides.Mix:
                _sampleProvider = _reader.ToSampleProvider().ToMono();
                break;
            }

            _chunk1 = new Chunk
            {
                Buffer = new float[ChunkSize],
                Offset = 0
            };
            _sampleProvider.Read(_chunk1.Buffer, 0, ChunkSize);
            _chunk2 = new Chunk
            {
                Buffer = new float[ChunkSize],
                Offset = ChunkSize
            };
            _sampleProvider.Read(_chunk2.Buffer, 0, ChunkSize);
        }
Beispiel #4
0
        /// <summary>
        /// Reading data from .wav and memory allocation for further processing
        /// </summary>
        /// <param name="ts"></param>
        /// <param name="fileName"></param>
        private void PreprocessRawData(TrackSelector ts, string fileName)
        {
            var reader = new WaveFileReader(fileName);

            switch (ts)
            {
            case TrackSelector.First:

                _data_Track1 = new float[reader.Length / 2];
                reader.ToSampleProvider().Read(_data_Track1, 0, _data_Track1.Length);
                _data_complex_Track1 = new Complex[reader.Length / 2];
                for (int i = 0; i < _data_Track1.Length; ++i)
                {
                    _data_complex_Track1[i] = new Complex(_data_Track1[i], 0);     //TODO: leave 0 or...?
                }
                _fft_frames_Track1 = new List <Complex[]>();
                PrepareFFTValues(ts);
                break;

            case TrackSelector.Second:

                _data_Track2 = new float[reader.Length / 2];
                reader.ToSampleProvider().Read(_data_Track2, 0, _data_Track2.Length);

                _data_complex_Track2 = new Complex[reader.Length / 2];
                for (int i = 0; i < _data_Track2.Length; ++i)
                {
                    _data_complex_Track2[i] = new Complex(_data_Track2[i], 0);
                }

                _fft_frames_Track2 = new List <Complex[]>();
                PrepareFFTValues(ts);
                break;

            case TrackSelector.File:
                _data_File = new float[reader.Length / 2];
                reader.ToSampleProvider().Read(_data_File, 0, _data_File.Length);

                _data_complex_FileData = new Complex[reader.Length / 2];
                for (int i = 0; i < _data_File.Length; ++i)
                {
                    _data_complex_FileData[i] = new Complex(_data_File[i], 0);
                }

                _fft_frames_FileData = new List <Complex[]>();
                PrepareFFTValues(ts);
                break;
            }
        }
Beispiel #5
0
        public static Stream ConvertWavToMp3(Stream wavStream)
        {
            _uniqueTempFileCounter += 1;
            var tempFile = Path.GetTempFileName();

            using (var rdr = new WaveFileReader(wavStream))
            {
                if (rdr.WaveFormat.BitsPerSample == 24)                                                           //Can't go from 24 bits wav to mp3 directly, create temporary 16 bit wav
                {
                    ISampleProvider sampleprovider = new Pcm24BitToSampleProvider(rdr);                           //24 bit to sample
                    var             resampler      = new WdlResamplingSampleProvider(sampleprovider, SampleRate); //sample to new sample rate
                    WaveFileWriter.CreateWaveFile16(tempFile, resampler);                                         //sample to actual wave file
                    return(ConvertWavFileToMp3MemoryStream(tempFile, true));                                      //file to mp3 bytes
                }
                else if (!SupportedMPEGSampleRates.Contains(rdr.WaveFormat.SampleRate))                           //Can't go from unsupported Sample Rate wav to mp3 directly
                {
                    var resampler = new WdlResamplingSampleProvider(rdr.ToSampleProvider(), SampleRate);          //sample to new sample rate
                    WaveFileWriter.CreateWaveFile16(tempFile, resampler);                                         //sample to actual wave file
                    return(ConvertWavFileToMp3MemoryStream(tempFile, true));                                      //file to mp3 bytes
                }
                else
                {
                    var retMs = FilesystemUtils.recyclableMemoryStreamManager.GetStream();
                    using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, BitRate))
                    {
                        rdr.CopyTo(wtr);
                        return(retMs);
                    }
                }
            }
        }
Beispiel #6
0
        private static void Mfcc()
        {
            const int windowSize = 2048;
            int       rate;
            var       data = new float[windowSize];

            // 2.5s のところから 2048 サンプル取得してくる
            using (var reader = new WaveFileReader(Path.Combine(CommonUtils.GetTrainingDataDirectory(), "あいうえお 2017-12-18 00-17-09.wav")))
            {
                var provider = reader.ToSampleProvider()
                               .Skip(TimeSpan.FromSeconds(2.5))
                               .ToMono();

                rate = provider.WaveFormat.SampleRate;

                for (var readSamples = 0; readSamples < data.Length;)
                {
                    var delta = provider.Read(data, readSamples, data.Length - readSamples);
                    if (delta == 0)
                    {
                        throw new EndOfStreamException();
                    }
                    readSamples += delta;
                }
            }

            var mfcc = new MfccAccord(rate, windowSize, 0, 8000, 24);

            foreach (var x in mfcc.ComputeMfcc12D(data))
            {
                Console.WriteLine(x);
            }
        }
Beispiel #7
0
        private static void ClassifyVowel()
        {
            var classifier = PrepareVowelClassifier();

            // 識別テスト
            const int windowSize = 2048;
            int       rate;
            var       data = new float[windowSize];

            using (var reader = new WaveFileReader(Path.Combine(CommonUtils.GetTrainingDataDirectory(), "校歌 2018-01-17 15-10-46.wav")))
            {
                var provider = reader.ToSampleProvider()
                               .Skip(TimeSpan.FromSeconds(11))
                               .ToMono();

                rate = provider.WaveFormat.SampleRate;

                for (var readSamples = 0; readSamples < data.Length;)
                {
                    var delta = provider.Read(data, readSamples, data.Length - readSamples);
                    if (delta == 0)
                    {
                        throw new EndOfStreamException();
                    }
                    readSamples += delta;
                }
            }

            Console.WriteLine(classifier.Decide(data, rate));
        }
Beispiel #8
0
        private static void MelFilteredSpectrum()
        {
            const int windowSize = 2048;
            const int sampleRate = 44100;

            var mfccComputer = new MfccAccord(sampleRate, windowSize, 0, 8000, 8);
            var hzAxis       = mfccComputer.HzAxisOfMelSpectrum();

            float[] ReadSamples(string fileName, double secs)
            {
                float[] xs;
                using (var wavReader = new WaveFileReader(Path.Combine(CommonUtils.GetTrainingDataDirectory(), fileName)))
                {
                    var provider = wavReader.ToSampleProvider().Skip(TimeSpan.FromSeconds(secs)).ToMono();

                    if (provider.WaveFormat.SampleRate != sampleRate)
                    {
                        throw new Exception();
                    }

                    xs = new float[windowSize];
                    for (var readSamples = 0; readSamples < xs.Length;)
                    {
                        var count = provider.Read(xs, readSamples, xs.Length - readSamples);
                        if (count == 0)
                        {
                            break;
                        }
                        readSamples += count;
                    }
                }
                return(xs);
            }

            void ShowSpectrum(string title, params (string, double)[] inputs)
Beispiel #9
0
 //test button
 private void testButton_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         new Task(() =>
         {
             WaveFileReader ws = new WaveFileReader(Properties.Resources.audiocheck_net_sin_1000Hz__3dBFS_3s);
             //WaveOutEvent output = new WaveOutEvent();
             //output.Init(ws);
             //output.Play();
             outputDevice = new WaveOutEvent();
             equalizer    = new SampleAggregator(ws.ToSampleProvider(), bands); //create new equalizer with mainReader as stream provider and bands as equalizer data
             //equalizer.NotificationCount = MainWindow.mainReader.WaveFormat.SampleRate / 100;
             equalizer.NotificationCount = ws.WaveFormat.SampleRate / 100;
             equalizer.PerformFFT        = true;
             equalizer.FftCalculated    += (s, a) => visualizerWindow.FftCalculatedFired(s, a);
             outputDevice.Init(equalizer); //Initialize equalizer in audio output
             outputDevice.Play();
             while (true)
             {
                 ws.CurrentTime = TimeSpan.FromSeconds(ws.TotalTime.TotalSeconds / 2);
                 Thread.Sleep(100);
             }
         }).Start();
     }
     catch (Exception ex)
     {
         Debug.WriteLine("\n" + ex + "\n");
     }
 }
        public async Task <IActionResult> Test()
        {
            try
            {
                var file = Request.Form.Files.First();

                int outRate = 44000;
                var source  = new RawSourceWaveStream(file.OpenReadStream(), new WaveFormat(outRate, 2));
                using (var wavFileReader = new WaveFileReader(source))
                {
                    var resampler  = new WdlResamplingSampleProvider(wavFileReader.ToSampleProvider(), 16000);
                    var monoSource = resampler.ToMono().ToWaveProvider16();

                    using (var outputStream = new MemoryStream())
                    {
                        WaveFileWriter.WriteWavFileToStream(outputStream, monoSource);
                        outputStream.Seek(0, SeekOrigin.Begin);

                        var result = await client.VerifyAsync(outputStream, Guid.Parse("fb786241-9f01-41cc-a585-50b65bd52c38"));

                        if (result.Result == Result.Accept)
                        {
                            // verification successful
                        }
                    }
                }
            }
            catch (Exception e)
            {
                int x = 1;
            }

            return(Ok());
        }
        public override Task AddTrainingDataAsync(string csvFileName)
        {
            float[] samples;
            int     rate;

            // 同じファイル名の .wav ファイルをロード
            using (var wavReader = new WaveFileReader(Path.ChangeExtension(csvFileName, ".wav")))
            {
                var provider = wavReader.ToSampleProvider().ToMono();
                rate = provider.WaveFormat.SampleRate;

                // 全サンプル読み込んじゃえ
                samples = new float[wavReader.SampleCount];
                for (var readSamples = 0; readSamples < samples.Length;)
                {
                    var count = provider.Read(samples, readSamples, samples.Length - readSamples);
                    if (count == 0)
                    {
                        break;
                    }
                    readSamples += count;
                }
            }

            var tasks = new List <Task>();

            using (var csvReader = new CsvReader(csvFileName, true))
            {
                const int windowSize = 2048;
                var       mfcc       = new MfccAccord(rate, windowSize, 0, 6000, 8);

                while (csvReader.ReadNextRecord())
                {
                    var time      = double.Parse(csvReader["Time"], CultureInfo.InvariantCulture);
                    var vowelType = ParseVowelType(csvReader["Class"]);

                    // どうしよう
                    if (vowelType == VowelType.Other)
                    {
                        continue;
                    }

                    // 並列でばんばか投げていくぞ
                    tasks.Add(Task.Run(() =>
                    {
                        var v = mfcc.MelSpectrum(new ReadOnlySpan <float>(samples, (int)(time * rate), windowSize));
                        v.Subtract(v.Mean(), v);

                        lock (this.TrainingData)
                            this.TrainingData.Add((v, vowelType));
                    }));
                }
            }

            return(Task.WhenAll(tasks));
        }
        public byte[] GenerateRadioMessageWavBytesFromFile(string fileName)
        {
            WaveFileReader  voiceReader   = new WaveFileReader(fileName);
            ISampleProvider voiceProvider = voiceReader.ToSampleProvider();

            byte[] bytes = DoRadioMix(voiceProvider, voiceReader.TotalTime);

            voiceReader.Close(); voiceReader.Dispose();

            return(bytes);
        }
Beispiel #13
0
        public static string GenerateAudio(ControllerContext context, string captcha)
        {
            var mixed = Path.GetTempFileName();
            var back  = Path.GetTempFileName();
            var main  = Path.GetTempFileName();



            //gera audio principal
            List <String> chars = new List <string>();

            foreach (var item in captcha)
            {
                chars.Add(context.HttpContext.Server.MapPath("~/Content/Audios/" + item.ToString() + ".wav"));
            }
            Concatenate(main, chars, 1000);

            chars = new List <string>();
            //gera audio aleatorio para sujeira
            for (int i = 0; i < 4; i++)
            {
                var randtext = Captcha.GenerateRandomCode(i);
                foreach (var item in randtext)
                {
                    chars.Add(context.HttpContext.Server.MapPath("~/Content/Audios/" + item.ToString() + ".wav"));
                }
            }
            Concatenate(mixed, chars, 0, true);
            ReverseWaveFile(mixed, back);


            using (var reader1 = new WaveFileReader(main))
                using (var reader2 = new WaveFileReader(back))
                {
                    var volumeProvider = new VolumeSampleProvider(reader2.ToSampleProvider());
                    volumeProvider.Volume = 0.15f;

                    var inputs = new List <ISampleProvider>()
                    {
                        reader1.ToSampleProvider(),
                        volumeProvider
                    };


                    var mixer = new MixingSampleProvider(inputs);
                    WaveFileWriter.CreateWaveFile16(mixed, mixer);
                }

            var mp3file = Path.GetTempFileName();

            WavToMp3(mixed, mp3file, context);

            return(mp3file);
        }
Beispiel #14
0
 public ResourceSound(string audioFileName)
 {
     FileName = audioFileName;
     using (var audioFileReader = new WaveFileReader(ExtractResourceStream(audioFileName)))
     {
         // TODO: could add resampling in here if required
         WaveFormat = audioFileReader.WaveFormat;
         var sampleProvider = audioFileReader.ToSampleProvider();
         AudioData = new float[audioFileReader.SampleCount];
         sampleProvider.Read(AudioData, 0, (int)audioFileReader.SampleCount);
     }
 }
Beispiel #15
0
        public static EncodedWavInfo EncodeWavToAdpcm(Stream stream, AdpcmFormat format)
        {
            var result = new EncodedWavInfo();

            result.Format = format;

            using (var waveReader = new WaveFileReader(stream))
            {
                result.SampleRate  = waveReader.WaveFormat.SampleRate;
                result.SampleCount = ( int )waveReader.SampleCount;

                // Try to find the smpl chunk containing loop info
                var smplChunk = waveReader.ExtraChunks.FirstOrDefault(x => x.IdentifierAsString == "smpl");
                if (smplChunk != null)
                {
                    using (var reader = new BinaryValueReader(waveReader, Amicitia.IO.Streams.StreamOwnership.Retain, Endianness.Big))
                    {
                        reader.Seek(smplChunk.StreamPosition + 0x24, SeekOrigin.Begin);
                        var sampleLoopCount = reader.ReadInt32();
                        if (sampleLoopCount > 0)
                        {
                            reader.Seek(0x04 + 0x08, SeekOrigin.Current);
                            result.HasLoop   = true;
                            result.LoopStart = reader.ReadInt32();
                            result.LoopEnd   = reader.ReadInt32();
                        }
                    }
                }

                // Get samples
                var sampleProvider = waveReader.ToSampleProvider();
                sampleProvider = sampleProvider.ToMono();

                var samples = new float[result.SampleCount];
                sampleProvider.Read(samples, 0, samples.Length);

                // Encode
                var pcm16 = Waveform.Pcm32ToPcm16(samples);
                result.History = new AdpcmHistory[Waveform.GetAdpcmFrameCount(pcm16.Length)];

                if (format == AdpcmFormat.Adpcm4)
                {
                    result.Data = Waveform.Pcm16ToAdpcm4(pcm16, result.History);
                }
                else
                {
                    throw new NotImplementedException();
                }
            }

            return(result);
        }
Beispiel #16
0
 private static ISampleProvider ReadWaveFile(WaveFileReader reader, CompositeDisposable disposables)
 {
     disposables.Add(reader);
     // if resampling is needed, do it.
     if (reader.WaveFormat.SampleRate != SampleRate)
     {
         var resampler = new MediaFoundationResampler(reader,
                                                      WaveFormat.CreateIeeeFloatWaveFormat(SampleRate, ChannelCount));
         disposables.Add(resampler);
         return(resampler.ToSampleProvider());
     }
     return(reader.ToSampleProvider());
 }
Beispiel #17
0
        public static AudioClip LoadWave(string filename)
        {
            using (WaveFileReader reader = new WaveFileReader(filename))
            {
                int sampleCount = (int)(reader.SampleCount * reader.WaveFormat.Channels);

                var audioData = new float[sampleCount];

                reader.ToSampleProvider().Read(audioData, 0, sampleCount);

                return(LoadInternal(filename, audioData, reader.WaveFormat.Channels, reader.WaveFormat.SampleRate));
            }
        }
Beispiel #18
0
        /// <summary>
        /// Converts data in Wav file into the specified format and reads data section of file (removes header) into AudioData buffer.
        /// </summary>
        /// <param name="originalFile" ></param>
        /// <param name="sampleRate"></param>
        private void ProcessWavFile(FileInfo originalFile)
        {
            byte[] temp = File.ReadAllBytes(AudioFile.FullName);

            using (MemoryStream stream = new MemoryStream(temp))
            {
                int channels;

                /*Read from the wav file's contents using stream */
                using (var inputReader = new WaveFileReader(stream))
                {
                    channels = inputReader.WaveFormat.Channels;

                    WdlResamplingSampleProvider resampler;

                    /*Stereo source. Must convert to mono with StereoToMonoSampleProvider */
                    if (channels == 2)
                    {
                        var monoSampleProvider = new StereoToMonoSampleProvider(inputReader.ToSampleProvider());
                        resampler = new WdlResamplingSampleProvider(monoSampleProvider, REQ_SAMPLE_RATE);
                    }
                    else
                    {
                        resampler = new WdlResamplingSampleProvider(inputReader.ToSampleProvider(), REQ_SAMPLE_RATE);
                    }


                    /*Write converted audio to overwrite the original wav file */
                    WaveFileWriter.CreateWaveFile16(AudioFile.FullName, resampler);
                }

                using (WaveFileReader reader = new WaveFileReader(AudioFile.FullName))
                {
                    AudioData = new byte[reader.Length];
                    reader.Read(AudioData, 0, (int)reader.Length);
                }
            }
        }
Beispiel #19
0
        private void CalculateAv()
        {
            if (filePath == null)
            {
                return;
            }
            // Calculate average ZCR and STE for 1-second window
            using (WaveFileReader reader = new WaveFileReader(filePath))
            {
                ISampleProvider sampleProvider = reader.ToSampleProvider();
                List <double>   zcrPerSecond   = new List <double>();

                // One second window
                int     windowSizeFloats = sampleProvider.WaveFormat.AverageBytesPerSecond / sizeof(float);
                float[] buffer           = new float[windowSizeFloats];
                avZcr = 0;
                avSte = 0;
                int windowsCount = 0;
                while (true)
                {
                    int samplesRead = sampleProvider.Read(buffer, 0, windowSizeFloats);
                    if (samplesRead <= 0)
                    {
                        break;
                    }

                    // Calculate ZCR in window
                    double sum = 0;
                    for (int i = 1; i < samplesRead; i++)
                    {
                        sum += Math.Abs(Math.Sign(buffer[i]) - Math.Sign(buffer[i - 1]));
                    }
                    double value = sum * sampleProvider.WaveFormat.SampleRate / (2.0 * samplesRead);
                    avZcr += value;

                    // Calculate STE in window
                    sum = 0;
                    for (int i = 0; i < samplesRead; i++)
                    {
                        sum += buffer[i] * buffer[i];
                    }
                    value  = sum / samplesRead;
                    avSte += value;

                    windowsCount++;
                }
                avZcr /= (double)windowsCount;
                avSte /= (double)windowsCount;
            }
        }
Beispiel #20
0
        public void ConvertAFile()
        {
            const string input = @"C:\Users\Mark\Downloads\Region-1.wav";

            if (!File.Exists(input))
            {
                Assert.Ignore("Test file not found");
            }
            using (var reader = new WaveFileReader(input))
            {
                var sp   = reader.ToSampleProvider();
                var wp24 = new SampleToWaveProvider24(sp);
                WaveFileWriter.CreateWaveFile(@"C:\Users\Mark\Downloads\Region1-24.wav", wp24);
            }
        }
Beispiel #21
0
        public void SoundCombo_SelectionChanged(string SelectedIndex)
        {
            StopWavePlayer();

            try
            {
                String mp3Path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\WinformControl\\alert" + SelectedIndex + ".wav";
                wavePlayer           = new WaveOut();
                reader               = new WaveFileReader(mp3Path);
                volumeSampleProvider = new VolumeSampleProvider(reader.ToSampleProvider());
                wavePlayer.Init(volumeSampleProvider);
                wavePlayer.Play();
            }
            catch { }
        }
Beispiel #22
0
        public void volumnSlider_PreviewMouseUp(float volumn, string SelectedIndex)
        {
            StopWavePlayer();

            try
            {
                String mp3Path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\WinformControl\\alert" + SelectedIndex + ".wav";
                wavePlayer                  = new WaveOut();
                reader                      = new WaveFileReader(mp3Path);
                volumeSampleProvider        = new VolumeSampleProvider(reader.ToSampleProvider());
                volumeSampleProvider.Volume = volumn;
                wavePlayer.Init(volumeSampleProvider);
                wavePlayer.Play();
            }
            catch { }
        }
Beispiel #23
0
        public static WaveSamples WavToWaveSamples(byte[] wavBytes)
        {
            var waveSamples = new WaveSamples();

            using (var inWavStream = new MemoryStream(wavBytes))
                using (var wavReader = new WaveFileReader(inWavStream))
                {
                    waveSamples.WaveFormat = wavReader.WaveFormat;
                    var sampleProvider = wavReader.ToSampleProvider();
                    var samples        = new float[inWavStream.Length];
                    var samplesCount   = sampleProvider.Read(samples, 0, samples.Length);
                    Array.Resize(ref samples, samplesCount);
                    waveSamples.Samples = samples;
                }
            return(waveSamples);
        }
 public Soundfile(string filename, int frameLength = 256, int beStart = 0, int beStop = 630)
 {
     using var wav = new WaveFileReader(filename);
     if (wav.WaveFormat.SampleRate != 22050 || wav.WaveFormat.BitsPerSample != 16 || wav.WaveFormat.Channels != 1)
     {
         throw new FileFormatException(new Uri(filename), "Wav file has to have a sample rate of 22050, 16 bits per sample and mono channel.");
     }
     this.FrameLength      = frameLength;
     this.SampleRate       = wav.WaveFormat.SampleRate;
     this.filename         = filename;
     this.BEFrequencyStart = beStart;
     this.BEFrequencyStop  = beStop;
     samples = (new float [wav.SampleCount]);
     wav.ToSampleProvider().Read(samples, 0, samples.Length);
     RefreshCalculations();
 }
 public static SampleSource CreateFromWaveFile(string fileName)
 {
     using (var reader = new WaveFileReader(fileName))
     {
         var sp            = reader.ToSampleProvider();
         var sourceSamples = (int)(reader.Length / (reader.WaveFormat.BitsPerSample / 8));
         var sampleData    = new float[sourceSamples];
         int n             = sp.Read(sampleData, 0, sourceSamples);
         if (n != sourceSamples)
         {
             throw new InvalidOperationException(String.Format("Couldn't read the whole sample, expected {0} samples, got {1}", n, sourceSamples));
         }
         var ss = new SampleSource(sampleData, sp.WaveFormat);
         return(ss);
     }
 }
Beispiel #26
0
        public CachedSound(UnmanagedMemoryStream ums)
        {
            using var waveFileReader = new WaveFileReader(ums);

            WaveFormat = waveFileReader.WaveFormat;
            var wholeFile      = new List <float>((int)(waveFileReader.Length / 4));
            var sampleProvider = waveFileReader.ToSampleProvider();
            var sourceSamples  = (int)(waveFileReader.Length / (waveFileReader.WaveFormat.BitsPerSample / 8));
            var sampleData     = new float[sourceSamples];
            int samplesRead;

            while ((samplesRead = sampleProvider.Read(sampleData, 0, sourceSamples)) > 0)
            {
                wholeFile.AddRange(sampleData.Take(samplesRead));
            }
            AudioData = wholeFile.ToArray();
        }
Beispiel #27
0
 public CachedSound(Stream sound)
 {
     using (var audioFileReader = new WaveFileReader(sound))
     {
         WaveFormat = audioFileReader.WaveFormat;
         var sp            = audioFileReader.ToSampleProvider();
         var wholeFile     = new List <float>((int)(audioFileReader.Length / 4));
         var sourceSamples = (int)(audioFileReader.Length / (audioFileReader.WaveFormat.BitsPerSample / 8));
         var sampleData    = new float[sourceSamples];
         int samplesread;
         while ((samplesread = sp.Read(sampleData, 0, sourceSamples)) > 0)
         {
             wholeFile.AddRange(sampleData.Take(samplesread));
         }
         AudioData = wholeFile.ToArray();
     }
 }
Beispiel #28
0
        public CachedSound(string audioFileName)
        {
            if (audioFileName.EndsWith(".mp3"))
            {
                using (Stream mp3File = Play.GetResourceStream(audioFileName))
                {
                    using (Mp3FileReader mp3FileReader = new Mp3FileReader(mp3File))
                    {
                        var sampleProvider = mp3FileReader.ToSampleProvider();

                        WaveFormat = sampleProvider.WaveFormat;
                        var wholeFile  = new List <float>((int)(mp3FileReader.Length / 4));
                        var readBuffer = new float[sampleProvider.WaveFormat.SampleRate * sampleProvider.WaveFormat.Channels];
                        int samplesRead;
                        while ((samplesRead = sampleProvider.Read(readBuffer, 0, readBuffer.Length)) > 0)
                        {
                            wholeFile.AddRange(readBuffer.Take(samplesRead));
                        }
                        AudioData = wholeFile.ToArray();
                    }
                }
            }
            else
            {
                using (Stream waveFile = Play.GetResourceStream(audioFileName))
                {
                    using (WaveFileReader waveFileReader = new WaveFileReader(waveFile))
                    {
                        var sampleProvider = waveFileReader.ToSampleProvider();


                        WaveFormat = sampleProvider.WaveFormat;
                        var wholeFile  = new List <float>((int)(waveFileReader.Length / 4));
                        var readBuffer = new float[sampleProvider.WaveFormat.SampleRate * sampleProvider.WaveFormat.Channels];
                        int samplesRead;
                        while ((samplesRead = sampleProvider.Read(readBuffer, 0, readBuffer.Length)) > 0)
                        {
                            wholeFile.AddRange(readBuffer.Take(samplesRead));
                        }
                        AudioData = wholeFile.ToArray();
                    }
                }
            }
        }
Beispiel #29
0
        public void playAlamSound(float volumn, string SoundIndex)
        {
            StopWavePlayer();

            try
            {
                String mp3Path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\WinformControl\\alert" + SoundIndex + ".wav";
                wavePlayer           = new WaveOut();
                reader               = new WaveFileReader(mp3Path);
                volumeSampleProvider = new VolumeSampleProvider(reader.ToSampleProvider());
                wavePlayer.Init(volumeSampleProvider);
                wavePlayer.Volume = volumn;
                wavePlayer.Play();
            }
            catch (Exception ex)
            {
                string sMsg = ex.Message.ToString();
            }
        }
Beispiel #30
0
        public void TestNAudio()
        {
            using (var reader = new WaveFileReader("Sound\\CAU1.wav"))
            {
                //WaveFormatConversionStream conv = new WaveFormatConversionStream(WaveFormat.CreateCustomFormat(WaveFormatEncoding.Pcm, 8000, 1, 8000, 1, 8), reader);

                var sp = new VolumeSampleProvider(reader.ToSampleProvider());
                sp.Volume = 0.5f;
                using (var writer = new WaveFileWriter("dv.wav", WaveFormat.CreateALawFormat(8000, 1)))
                {
                    int sampleCount = (int)reader.SampleCount;
                    var buff        = new float[sampleCount];
                    sp.Read(buff, 0, sampleCount);
                    writer.WriteSamples(buff, 0, sampleCount);
                    writer.Close();
                }
                reader.Close();
            }
        }