Ejemplo n.º 1
0
        /// <summary>
        /// Mixes two wav files to a single wav file. (Unused).
        /// </summary>
        public void mix()
        {
            window.lockForMixing();

            WaveFileReader reader1 = new WaveFileReader(file1);
            WaveFileReader reader2 = new WaveFileReader(file2);

            int        maxSampleRate = Math.Max(reader1.WaveFormat.SampleRate, reader2.WaveFormat.SampleRate);
            WaveFormat format        = new WaveFormat(maxSampleRate, 1);

            MediaFoundationResampler resampler1 = new MediaFoundationResampler(reader1, format);
            var input1 = resampler1.ToSampleProvider();
            MediaFoundationResampler resampler2 = new MediaFoundationResampler(reader2, format);
            var input2 = resampler2.ToSampleProvider();

            ISampleProvider[] provider = { input1, input2 };

            MixingSampleProvider mixer = new MixingSampleProvider(provider);

            WaveFileWriter.CreateWaveFile16(mixfile, mixer);

            resampler1.Dispose();
            resampler2.Dispose();
            reader1.Close();
            reader2.Close();
            reader1.Dispose();
            reader2.Dispose();

            window.unlock();
        }
Ejemplo n.º 2
0
        public Vector LoadFromMp3(string path)
        {
            List <double> semplList = new List <double>();

            using (Mp3FileReader reader = new Mp3FileReader(path))
            {
                MediaFoundationResampler outFormat = Resampler(reader);// to 8kHz
                ISampleProvider          semples   = outFormat.ToSampleProvider().ToMono();
                Fd = semples.WaveFormat.SampleRate;

                float[] fl = new float[Setting.BufferSize];
                int     m;
                do
                {
                    m = semples.Read(fl, 0, Setting.BufferSize);

                    for (int i = 0; i < Setting.BufferSize; i++)
                    {
                        semplList.Add(fl[i]);
                    }
                }while (m == Setting.BufferSize);
            }

            return(semplList.ToArray());
        }
Ejemplo n.º 3
0
    static ShazamResult CaptureAndTag()
    {
        var analysis = new Analysis();
        var finder   = new LandmarkFinder(analysis);

        using (var capture = new WasapiCapture()) {
            var captureBuf = new BufferedWaveProvider(capture.WaveFormat)
            {
                ReadFully = false
            };

            capture.DataAvailable += (s, e) => {
                captureBuf.AddSamples(e.Buffer, 0, e.BytesRecorded);
            };

            capture.StartRecording();

            using (var resampler = new MediaFoundationResampler(captureBuf, new WaveFormat(Analysis.SAMPLE_RATE, 16, 1))) {
                var sampleProvider = resampler.ToSampleProvider();
                var retryMs        = 3000;
                var tagId          = Guid.NewGuid().ToString();

                while (true)
                {
                    while (captureBuf.BufferedDuration.TotalSeconds < 1)
                    {
                        Thread.Sleep(100);
                    }

                    analysis.ReadChunk(sampleProvider);

                    if (analysis.StripeCount > 2 * LandmarkFinder.RADIUS_TIME)
                    {
                        finder.Find(analysis.StripeCount - LandmarkFinder.RADIUS_TIME - 1);
                    }

                    if (analysis.ProcessedMs >= retryMs)
                    {
                        //new Painter(analysis, finder).Paint("c:/temp/spectro.png");
                        //new Synthback(analysis, finder).Synth("c:/temp/synthback.raw");

                        var sigBytes = Sig.Write(Analysis.SAMPLE_RATE, analysis.ProcessedSamples, finder);
                        var result   = ShazamApi.SendRequest(tagId, analysis.ProcessedMs, sigBytes).GetAwaiter().GetResult();
                        if (result.Success)
                        {
                            return(result);
                        }

                        retryMs = result.RetryMs;
                        if (retryMs == 0)
                        {
                            return(result);
                        }
                    }
                }
            }
        }
    }
Ejemplo n.º 4
0
        private void ProcessAudioFile(string inputFilePath, string outputFilePath)
        {
            using var reader = new AudioFileReader(inputFilePath);

            var mono         = new StereoToMonoSampleProvider(reader);
            var outputFormat = new WaveFormat(OutputRate, mono.WaveFormat.Channels);

            using var resampler = new MediaFoundationResampler(mono.ToWaveProvider(), outputFormat);
            WaveFileWriter.CreateWaveFile16(outputFilePath, resampler.ToSampleProvider());
        }
Ejemplo n.º 5
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());
 }
Ejemplo n.º 6
0
        /// <summary>
        /// 渲染音乐
        /// </summary>
        /// <param name="outFile">输出文件</param>
        public void Render(string outFile)
        {
            int sleepTime = Convert.ToInt32((60.0 / Bpm) * 1000.0);

            byte[] buffer = new byte[1024];
            var    ms     = new MemoryStream();
            var    rs     = new RawSourceWaveStream(ms, new WaveFormat(16000, 16, 2));
            List <ISampleProvider> resultSound = new List <ISampleProvider>();
            int count = 1;

            foreach (var beat in Notes)
            {
                List <ISampleProvider> notesSound = new List <ISampleProvider>();
                foreach (var note in beat.GetNotes())
                {
                    var _reader = new AudioFileReader(note.Instrument.GetFile(note.pName, note.Octive, note.Dynam));
                    _reader.Volume = note.Volume;
                    var outFormat = new WaveFormat(44100, _reader.WaveFormat.Channels);
                    var resampler = new MediaFoundationResampler(_reader, outFormat);
                    var _trimmed  = new OffsetSampleProvider(resampler.ToSampleProvider())
                    {
                        Take = new TimeSpan(0, 0, 0, 0, sleepTime * note.Duration)
                    };
                    notesSound.Add(_trimmed);
                }
                count++;
                if (notesSound.Count > 0)
                {
                    var mixer   = new MixingSampleProvider(notesSound);
                    var trimmed = new OffsetSampleProvider(mixer)
                    {
                        DelayBy = TimeSpan.FromMilliseconds(count * sleepTime)
                    };
                    resultSound.Add(trimmed);
                }
            }
            var ResultMixer = new MixingSampleProvider(resultSound);

            WaveFileWriter.CreateWaveFile16(outFile, ResultMixer);
        }
        /// <summary>
        /// Creates Sample provider for cached AudioData.
        /// </summary>
        /// <param name="audioData">Audio data.</param>
        /// <param name="playbackToken">Playback token.</param>
        /// <param name="masterVolumeProvider">Master volume provider.</param>
        /// <param name="volume">Volume for audio playback.</param>
        /// <param name="useParallel">true if use parallel.</param>
        public AudioDataFileSampleProvider(AudioData audioData, PlaybackToken playbackToken, IMasterVolumeProvider masterVolumeProvider, float volume = 1.0f, bool useParallel = false)
            : base(audioData, playbackToken, masterVolumeProvider, volume, useParallel)
        {
            string filePath = audioData.FilePath;

            if (filePath != null)
            {
                this.reader = new AudioFileReader(filePath);
                this.isAudioFileReaderDisposed = false;

                this.resampler = AudioData.CreateResampler(this.reader, audioData.WaveFormat, audioData.ResamplingQuality);

                if (this.resampler != null)
                {
                    this.stream = resampler.ToSampleProvider();
                }
                else
                {
                    this.stream = reader;
                }
            }
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Class constructor.
 /// </summary>
 public CachedSound(string file, int sampleRate, int channels, float volume = 1.0f)
 {
     using (AudioFileReader reader = new AudioFileReader(file))
     {
         reader.Volume = volume;
         if ((reader.WaveFormat.SampleRate == sampleRate) && (reader.WaveFormat.Channels == channels))
         {
             List <float> wholeFile = new List <float>((int)(reader.Length / 4));
             float[]      buffer    = new float[reader.WaveFormat.SampleRate * reader.WaveFormat.Channels];
             int          samplesRead;
             while ((samplesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
             {
                 wholeFile.AddRange(buffer.Take(samplesRead));
             }
             AudioData  = wholeFile.ToArray();
             WaveFormat = reader.WaveFormat;
         }
         else
         {
             WaveFormat newFormat = new WaveFormat(sampleRate, channels);
             using (MediaFoundationResampler resampler = new MediaFoundationResampler(reader, newFormat))
             {
                 ISampleProvider sampleProvider = resampler.ToSampleProvider();
                 List <float>    wholeFile      = new List <float>();
                 float[]         buffer         = new float[newFormat.SampleRate * newFormat.Channels];
                 int             samplesRead;
                 while ((samplesRead = sampleProvider.Read(buffer, 0, buffer.Length)) > 0)
                 {
                     wholeFile.AddRange(buffer.Take(samplesRead));
                 }
                 AudioData  = wholeFile.ToArray();
                 WaveFormat = newFormat;
             }
         }
     }
 }
Ejemplo n.º 9
0
        public static void StartNewTrack()
        {
            // find out what to play
            var tracks = FindTracks().ToArray();
            var track  = tracks.Where(t => t.Mood == CurrentMood).PickRandom();

            if (track == null)
            {
                // no music? try another mood
                var others = tracks;
                if (others.Any())
                {
                    track = others.PickRandom();
                }
            }
            if (track == null)
            {
                // no music at all :(
                return;
            }

            // prepare the new track
            var           tl = track.Path.ToLower();
            WaveChannel32 wc = null;

            if (tl.EndsWith("ogg"))
            {
                wc = new WaveChannel32(new VorbisWaveReader(track.Path));
            }
            else if (tl.EndsWith("mp3"))
            {
                wc = new WaveChannel32(new Mp3FileReader(track.Path));
            }
            else if (tl.EndsWith("wav"))
            {
                wc = new WaveChannel32(new WaveFileReader(track.Path));
            }
            else
            {
                throw new Exception("Unknown audio format for file " + track.Path);
            }

            // convert to a standard format so we can mix them (e.g. a mp3 with an ogg)
            var resampler = new MediaFoundationResampler(wc, waveFormat);
            var sp        = resampler.ToSampleProvider();

            // setup our track
            wc.Volume        = musicVolume;
            wc.PadWithZeroes = false;             // to allow PlaybackStopped event to fire

            // fade between the two tracks
            mixer.RemoveMixerInput(prevTrack);
            prevTrack = curTrack;
            if (prevTrack != null)
            {
                prevTrack.BeginFadeOut(FadeDuration);
            }
            curTrack = new FadeInOutSampleProvider(sp, true);
            curTrack.BeginFadeIn(FadeDuration);
            mixer.AddMixerInput(curTrack);
            waveout.Play();
            IsPlaying = true;
        }
Ejemplo n.º 10
0
        private static void ConvertSound(Sound sound)
        {
            if (!sound.HasStartFile && !sound.HasStartFile)
            {
                return;
            }

            FileInfo outFile = CurrentDirectory.GetDirectory("out").GetFile($"{sound.Name}.{Arguments.Format.ToString().ToLower()}");

            if (!Arguments.Overwrite && outFile.Exists)
            {
                return;
            }

            FileInfo tempWave = new FileInfo(Path.GetTempFileName());

            WaveReader reader = new WaveReader();
            AudioData  audio  = null;

            Console.WriteLine($"Processing {sound.Name}...");
            if (sound.HasStartFile && !sound.HasLoopFile)
            {
                using (VorbisWaveReader vorbisStart = new VorbisWaveReader(GameSounds.GetFile(sound.StartFileName).FullName))
                {
                    WaveFileWriter.CreateWaveFile(tempWave.FullName, vorbisStart.ToWaveProvider16());
                }
                using (FileStream stream = tempWave.OpenRead())
                {
                    audio = reader.Read(stream);
                }
            }
            else if (sound.HasStartFile && sound.HasLoopFile)
            {
                VorbisWaveReader vorbisStart = new VorbisWaveReader(GameSounds.GetFile(sound.StartFileName).FullName);
                VorbisWaveReader vorbisLoop  = new VorbisWaveReader(GameSounds.GetFile(sound.LoopFileName).FullName);
                if (vorbisStart.WaveFormat.SampleRate < vorbisLoop.WaveFormat.SampleRate)
                {
                    MediaFoundationResampler sampeler = new MediaFoundationResampler(vorbisStart, vorbisLoop.WaveFormat.SampleRate);
                    WaveFileWriter.CreateWaveFile(tempWave.FullName, sampeler.ToSampleProvider().FollowedBy(vorbisLoop).ToWaveProvider16());
                }
                else if (vorbisStart.WaveFormat.SampleRate > vorbisLoop.WaveFormat.SampleRate)
                {
                    MediaFoundationResampler sampeler = new MediaFoundationResampler(vorbisLoop, vorbisStart.WaveFormat.SampleRate);
                    WaveFileWriter.CreateWaveFile(tempWave.FullName, vorbisStart.FollowedBy(sampeler.ToSampleProvider()).ToWaveProvider16());
                }
                else
                {
                    WaveFileWriter.CreateWaveFile(tempWave.FullName, vorbisStart.FollowedBy(vorbisLoop).ToWaveProvider16());
                }
                VorbisReader dataStart = new VorbisReader(GameSounds.GetFile(sound.StartFileName).FullName);
                VorbisReader dataLoop  = new VorbisReader(GameSounds.GetFile(sound.LoopFileName).FullName);
                int          startLoop = (int)dataStart.TotalSamples;
                int          endLoop   = (int)dataStart.TotalSamples + (int)dataLoop.TotalSamples;
                vorbisStart.Dispose();
                vorbisLoop.Dispose();
                dataStart.Dispose();
                dataLoop.Dispose();
                using (FileStream stream = tempWave.OpenRead())
                {
                    audio = reader.Read(stream);
                }

                audio.SetLoop(true, startLoop, endLoop);
            }
            else if (!sound.HasStartFile && sound.HasLoopFile)
            {
                VorbisWaveReader vorbisLoop = new VorbisWaveReader(GameSounds.GetFile(sound.LoopFileName).FullName);
                WaveFileWriter.CreateWaveFile(tempWave.FullName, vorbisLoop.ToWaveProvider16());
                VorbisReader dataLoop     = new VorbisReader(GameSounds.GetFile(sound.LoopFileName).FullName);
                int          totalSamples = (int)dataLoop.TotalSamples;
                vorbisLoop.Dispose();
                dataLoop.Dispose();
                audio = reader.Read(tempWave.OpenRead());

                audio.SetLoop(true, 0, totalSamples);
            }

            if (audio != null)
            {
                BCFstmWriter writer = new BCFstmWriter(Arguments.Target);
                writer.Configuration.Codec      = Arguments.Codec;
                writer.Configuration.Endianness = Arguments.Endianness;
                using (FileStream stream = outFile.OpenWrite())
                {
                    writer.WriteToStream(audio, stream);
                }
            }
        }
Ejemplo n.º 11
0
        private static async Task <bool> MakeAudioConfigAsync(SpeechHandler handler)
        {
            // var audioConfig = AudioConfig.FromWavFileInput(@"D:\Users\ManabuTonosaki\OneDrive - tomarika\tono.wav");
            // var audioConfig = AudioConfig.FromDefaultMicrophoneInput();

            Debug.Assert(handler.Device != null);

            var wavein        = new WasapiLoopbackCapture(handler.Device);
            var waveoutFormat = new WaveFormat(16000, 16, 1);
            var lastSpeakDT   = DateTime.Now;
            var willStop      = DateTime.MaxValue;

            wavein.DataAvailable += (s, e) =>
            {
                if (e.BytesRecorded > 0)
                {
                    using var ms   = new MemoryStream(e.Buffer, 0, e.BytesRecorded);
                    using var rs   = new RawSourceWaveStream(ms, wavein.WaveFormat);
                    using var freq = new MediaFoundationResampler(rs, waveoutFormat.SampleRate);
                    var w16 = freq.ToSampleProvider().ToMono().ToWaveProvider16();
                    var len = w16.Read(handler.buf, 0, handler.buf.Length);
                    handler.AudioInputStream.Write(handler.buf, len);

                    lastSpeakDT = DateTime.Now;
                    willStop    = DateTime.MaxValue;
                }
                else
                {
                    if (DateTime.Now < willStop)
                    {
                        if (willStop == DateTime.MaxValue)
                        {
                            willStop = DateTime.Now + TimeSpan.FromSeconds(10);
                        }
                        var silence = new SilenceProvider(waveoutFormat);
                        var len     = silence.Read(handler.buf, 0, waveoutFormat.BitsPerSample * waveoutFormat.SampleRate / 8 / 100); // 10ms
                        var cnt     = (int)((DateTime.Now - lastSpeakDT).TotalMilliseconds / 10);
                        for (var i = 0; i < cnt; i++)
                        {
                            handler.AudioInputStream.Write(handler.buf, len);
                        }
                        lastSpeakDT = DateTime.Now;
                    }
                }
            };

            var audioformat = AudioStreamFormat.GetWaveFormatPCM(samplesPerSecond: 16000, bitsPerSample: 16, channels: 1);

            handler.AudioInputStream = AudioInputStream.CreatePushStream(audioformat);
            handler.AudioConfig      = AudioConfig.FromStreamInput(handler.AudioInputStream);

            await Task.Delay(100);

            handler.StopRequested += (s, e) =>
            {
                wavein.StopRecording();
            };
            wavein.StartRecording();

            return(true);
        }
Ejemplo n.º 12
0
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            settings.IsProcessing     = true;
            progBarMessage.Visibility = Visibility.Visible;

            settings.StartEnabled   = false;
            settings.ProcessEnabled = false;

            var calculate = Task.Factory.StartNew(() =>
            {
                prgrs.Report(0);

                audioFile = new AudioFileReader(settings.InputFile);
                audioFile.ToStereo();

                var n = audioFile.Length / (audioFile.WaveFormat.BitsPerSample / 8) / audioFile.WaveFormat.Channels;

                var outFormat = new WaveFormat(settings.SampleRate, 2);
                ISampleProvider wave;

                using (var resampler = new MediaFoundationResampler(audioFile, outFormat))
                {
                    wave = resampler.ToSampleProvider();
                }

                //MessageBox.Show(audioFile.WaveFormat.Channels.ToString());

                //audioFile.ToMono();
                //audioFile.ToStereo();

                var bits = wave.WaveFormat.BitsPerSample;
                var Fs   = wave.WaveFormat.SampleRate;

                //MessageBox.Show(Fs.ToString());

                var channels = wave.WaveFormat.Channels;

                //string outpath = @"E:\states.dat";
                string outwav = settings.OutputFile;

                float FS = settings.SampleRate;

                prgrs.Report(10);
                Thread.Sleep(200);

                using (WaveFileWriter outWavFile = new WaveFileWriter(outwav, new WaveFormat((int)FS, 16, 2)))
                {
                    float period    = settings.Period; // ms
                    double fullPath = period;

                    int bb    = 0;
                    int i     = 0;
                    bool mode = false;

                    do
                    {
                        if (i % 1000 == 0)
                        {
                            prgrs.Report((int)(i / (float)n * 100 * 0.9f + 10f));
                        }

                        float[] samples = new float[2];
                        bb           = wave.Read(samples, 0, samples.Length);
                        var leftVal  = samples[0];
                        var rightVal = samples[1];

                        var curPath = (i * 1000f / FS);

                        if (curPath >= fullPath)
                        {
                            mode     = !mode;
                            fullPath = fullPath + period;
                        }

                        if (mode == true)
                        {
                            leftVal = 0;
                        }
                        else
                        {
                            rightVal = 0;
                        }

                        //writer.Write(leftVal);
                        //writer.Write(rightVal);

                        outWavFile.WriteSample(leftVal);
                        outWavFile.WriteSample(rightVal);

                        i++;
                    } while (bb > 0);


                    prgrs.Report(95);
                    //writer.Flush();
                    //writer.Close();
                    outWavFile.Flush();
                    prgrs.Report(100);

                    outWavFile.Close();
                }

                //outputDevice.Init(audioFile);
            });

            calculate.GetAwaiter().OnCompleted(() =>
            {
                settings.IsProcessing     = false;
                progBarMessage.Visibility = Visibility.Hidden;

                settings.StartEnabled   = true;
                settings.ProcessEnabled = true;
                MessageBox.Show("Готово!");

                prgrs.Report(0);
            });
        }
Ejemplo n.º 13
0
        private static async Task MusicPlayLoop(DiscordChannel channel, ConnectionModel connection)
        {
            try
            {
                while (connection.Connected)
                {
                    if (connection.Songs.TryDequeue(out SongModel model))
                    {
                        await channel.SendMessageAsync($"Now Playing: **{model}**");

                        try
                        {
                            using (MediaFoundationReader reader = new MediaFoundationReader(model.FilePath))
                                using (MediaFoundationResampler resampler = new MediaFoundationResampler(reader, 48000))
                                {
                                    VolumeSampleProvider volume = new VolumeSampleProvider(resampler.ToSampleProvider())
                                    {
                                        Volume = connection.Volume
                                    };
                                    connection.SampleProvider = volume;
                                    IWaveProvider waveProvider = connection.SampleProvider.ToWaveProvider16();

                                    connection.Total      = reader.TotalTime;
                                    connection.NowPlaying = model;

                                    byte[] buff = new byte[3840];
                                    int    br   = 0;

                                    await connection.Connection.SendSpeakingAsync(true);

                                    while ((br = waveProvider.Read(buff, 0, buff.Length)) > 0)
                                    {
                                        connection.Token.ThrowIfCancellationRequested();

                                        if (connection.Skip)
                                        {
                                            break;
                                        }

                                        if (br < buff.Length)
                                        {
                                            for (int i = br; i < buff.Length; i++)
                                            {
                                                buff[i] = 0;
                                            }
                                        }

                                        connection.Elapsed = reader.CurrentTime;

                                        await connection.Connection.SendAsync(buff, 20);

                                        connection.RecordBuffer.AddSamples(buff, 0, buff.Length);
                                    }

                                    if (connection.Connected)
                                    {
                                        await connection.Connection.SendSpeakingAsync(false);
                                    }

                                    connection.Skip = false;
                                }
                        }
                        catch (OperationCanceledException) { break; }
                        catch (InvalidOperationException) { break; }
                        catch (Exception ex)
                        {
                            await channel.SendMessageAsync($"Something went a bit wrong attempting to play that and a {ex.GetType().Name} was thrown. Sorry!\r\n{ex.Message}");
                        }
                    }

                    connection.NowPlaying = null;
                    connection.Skip       = false;

                    await Task.Delay(500);
                }
            }
            catch
            {
                if (connection.Connected)
                {
                    throw;
                }
            }
        }