Ejemplo n.º 1
0
        /// <summary>Creates a new `AudioFile` from a `WaveStream` input. Also resamples the input and optionally converts it to single-channel audio.</summary>
        /// <param name="source">The input audio data (typically finite).</param>
        /// <param name="targetSampleRate">Used to resample the `WaveStream` input. This should match the sample rate (in Hz) the `Analyzer` is using (via `Config.SampleRate`).</param>
        /// <param name="forceMono">Toggles conversion of multi-channel audio to mono.</param>
        public AudioFile(WaveStream source, int targetSampleRate, bool forceMono = true)
        {
            this.source = source;

            var samples = forceMono ? source.ToSampleProvider().AsMono() : source.ToSampleProvider();

            this.samples = samples.Resample(targetSampleRate);
        }
Ejemplo n.º 2
0
        private void Speedtb_TextChanged(object sender, EventArgs e)
        {
            if (reader == null)
            {
                return;
            }
            try
            {
                float speed;
                if (!float.TryParse(Speedtb.Text, out speed))
                {
                    throw new Exception("speed value not valid");
                }

                //speed
                var useTempo = radioButton1.Checked;
                speedControl = new VarispeedSampleProvider(reader.ToSampleProvider(), 100, new SoundTouchProfile(useTempo, false));
                speedControl.PlaybackRate = speed;

                var state = wout.PlaybackState == PlaybackState.Playing;
                wout?.Stop();
                wout = new WaveOut();///
                wout.Init(speedControl);

                if (state)
                {
                    wout.Play();
                }
                //wout.Init(reader2);
            }
            catch
            {
                //MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 3
0
        private static void WriteNormalizedAudio(string path, [NotNull] WaveStream reader)
        {
            var sampleReader = reader.ToSampleProvider();

            // find the max peak
            float max    = 0;
            var   buffer = new float[reader.WaveFormat.SampleRate];
            int   read;

            do
            {
                read = sampleReader.Read(buffer, 0, buffer.Length);
                if (read > 0)
                {
                    max = Math.Max(max, Enumerable.Range(0, read).Select(i => Math.Abs(buffer[i])).Max());
                }
            } while (read > 0);

            if (Math.Abs(max) < float.Epsilon || max > 1.0f)
            {
                throw new InvalidOperationException("Audio normalization failed to find a reasonable peak volume");
            }

            // rewind and amplify
            reader.Position = 0;

            // write out to a new WAV file
            WaveFileWriter.CreateWaveFile16(path, new GainSampleProvider(sampleReader, 1 / max - 0.05f));
        }
Ejemplo n.º 4
0
        private static IWaveProvider CreateWaveConverter(WaveFormat format, WaveStream stream)
        {
            if (stream.WaveFormat.Encoding != WaveFormatEncoding.IeeeFloat)
            {
                try
                {
                    return(new WaveFormatConversionStream(format, stream));
                }
                catch (Exception exc)
                { // This happens for example with floating point wave files.
                    logger.Warn(exc, "'WaveFormatConversionStream' failed. Attempting to use sample provider conversion now.");
                }
            }

            // Try going through the sample provider and then remix/resample manually if necessary...
            ISampleProvider sampleProvider = stream.ToSampleProvider();

            if (sampleProvider.WaveFormat.Channels > 1)
            {
                sampleProvider = new StereoToMonoSampleProvider(sampleProvider);
            }
            if (sampleProvider.WaveFormat.SampleRate != format.SampleRate)
            {
                sampleProvider = new WdlResamplingSampleProvider(sampleProvider, format.SampleRate);
            }
            return(sampleProvider.ToWaveProvider16());
        }
Ejemplo n.º 5
0
        public static float[] GetSamples(WaveStream waveStream)
        {
            ISampleProvider provider = waveStream.ToSampleProvider();

            if (provider.WaveFormat.SampleRate != 44100)
            {
                provider = new WdlResamplingSampleProvider(provider, 44100);
            }
            if (provider.WaveFormat.Channels > 1)
            {
                provider = new StereoToMonoSampleProvider(provider)
                {
                    LeftVolume  = 1,
                    RightVolume = 0,
                };
            }
            List <float> samples = new List <float>();

            float[] buffer = new float[128 * 1024];
            int     n;

            while ((n = provider.Read(buffer, 0, buffer.Length)) > 0)
            {
                samples.AddRange(buffer.Take(n));
            }
            return(samples.ToArray());
        }
Ejemplo n.º 6
0
 public void Play()
 {
     effectStream = new EffectStream(outStream.ToSampleProvider());
     effectStream.UpdateEffectChain(effectChain.ToArray());
     CreatePlayer();
     player.Init(effectStream);
     player.Play();
 }
Ejemplo n.º 7
0
 public SoundInstanceMono(WaveStream file)
 {
     this.Pan         = 0.5f;
     this.Volume      = 1f;
     this._sampler    = file.ToSampleProvider();
     this._file       = file;
     this._waveFormat = new WaveFormat(this._file.WaveFormat.SampleRate, 2);
     this._buffer     = new float[2048];
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Initializes a new instance of AudioFileReader
        /// </summary>
        /// <param name="fileName">The file to open</param>
        public AudioFileReaderVVVV(string fileName)
        {
            FLockObject   = new object();
            this.FileName = fileName;
            CreateReaderStream(fileName);
            FSourceBytesPerSample = (FReaderStream.WaveFormat.BitsPerSample / 8) * FReaderStream.WaveFormat.Channels;

            this.FSampleChannel = new VolumeSampleProvider(FReaderStream.ToSampleProvider());
            FDestBytesPerSample = 4 * FSampleChannel.WaveFormat.Channels;
            FLength             = SourceToDest(FReaderStream.Length);
        }
Ejemplo n.º 9
0
 internal WdlResampling16Stream([NotNull] WaveStream sourceStream, int sampleRate)
 {
     _sourceStream         = sourceStream;
     _sourceSampleProvider = sourceStream.ToSampleProvider();
     _sampleProvider       = new WdlResamplingSampleProvider(_sourceSampleProvider, sampleRate);
     // WdlResamplingSampleProvider always outputs IEEE float samples, so a 16-bit PCM wrapper is required.
     // See the source code of WdlResamplingSampleProvider in NAudio.
     // The wrapping technique is adapted from WaveFileWriter.CreateWaveFile16(), inspired from
     // Mark Heath's (creator of NAudio) article: http://markheath.net/post/fully-managed-input-driven-resampling-wdl.
     _to16Provider = new SampleToWaveProvider16(_sampleProvider);
 }
Ejemplo n.º 10
0
        public static float[] BuildPeaks(WaveStream stream, IProgress <int> progress)
        {
            const double peaksRate = 4000;

            float[] peaks;
            int     channels     = stream.WaveFormat.Channels;
            double  peaksSamples = (int)((double)stream.Length / stream.WaveFormat.BlockAlign / stream.WaveFormat.SampleRate * peaksRate);

            peaks = new float[(int)(peaksSamples + 1) * channels];
            double blocksPerPixel = stream.Length / stream.WaveFormat.BlockAlign / peaksSamples;

            var sampleProvider = stream.ToSampleProvider();

            float[] buffer = new float[128 * 1024];

            int    readPos = 0;
            int    peaksPos = 0;
            double bufferPos = 0;
            float  lmax = 0, lmin = 0, rmax = 0, rmin = 0;
            int    lastProgress = 0;
            int    n;

            while ((n = sampleProvider.Read(buffer, 0, buffer.Length)) != 0)
            {
                readPos += n;
                for (int i = 0; i < n; i += channels)
                {
                    lmax = Math.Max(lmax, buffer[i]);
                    lmin = Math.Min(lmin, buffer[i]);
                    if (channels > 1)
                    {
                        rmax = Math.Max(rmax, buffer[i + 1]);
                        rmin = Math.Min(rmin, buffer[i + 1]);
                    }
                    if (i > bufferPos)
                    {
                        lmax = -lmax; lmin = -lmin; rmax = -rmax; rmin = -rmin; // negate peaks to fipped waveform
                        peaks[peaksPos * channels]     = lmax == 0 ? lmin : lmin == 0 ? lmax : (lmin + lmax) / 2;
                        peaks[peaksPos * channels + 1] = rmax == 0 ? rmin : rmin == 0 ? rmax : (rmin + rmax) / 2;
                        peaksPos++;
                        lmax       = lmin = rmax = rmin = 0;
                        bufferPos += blocksPerPixel * stream.WaveFormat.Channels;
                    }
                }
                bufferPos -= n;
                int newProgress = (int)((double)readPos * sizeof(float) * 100 / stream.Length);
                if (newProgress != lastProgress)
                {
                    progress.Report(newProgress);
                }
            }
            return(peaks);
        }
Ejemplo n.º 11
0
        private void makeFasterToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (reader == null)
            {
                return;
            }
            var data = GetDataOf16Bit2ChannelFile(reader);

            int newSize = data.Length / 2;

            if (data.Length % 2 != 0)
            {
                newSize++;
            }

            short[] newData = new short[newSize];
            for (int i = 0; i < newSize; i += 4)
            {
                newData[i / 2]     = data[i];
                newData[i / 2 + 1] = data[i + 1];
            }

            MemoryStream mstream = new MemoryStream();
            BinaryWriter writer  = new BinaryWriter(mstream);

            foreach (var item in data)
            {
                writer.Write(item);
            }

            var useTempo = radioButton1.Checked;

            reader       = new RawSourceWaveStream(mstream, reader.WaveFormat);
            speedControl = new VarispeedSampleProvider(reader.ToSampleProvider(), 100, new SoundTouchProfile(useTempo, false));

            var state = wout?.PlaybackState == PlaybackState.Playing;

            wout?.Stop();
            hScrollBar11.Value = 0;
            progressBar1.Value = 0;
            wout = new WaveOut();///
            wout.Init(speedControl);

            if (state)
            {
                wout.Play();
            }

            return;
        }
Ejemplo n.º 12
0
 protected WaveStreamSoundFX(WaveStream reader)
 {
     lock (_lock) {
         if (reader == null)
         {
             throw new ArgumentNullException(I18NString.Lookup("NullPointer"));
         }
         this.reader      = reader;
         this.length      = reader.TotalTime;
         this.source      = reader.ToSampleProvider();
         this.canSeek     = true;
         this.audioFormat = SFXUtilities.FromWaveFormat(reader.WaveFormat);
     }
 }
Ejemplo n.º 13
0
        public bool Load(string path, Guid device)
        {
            var cext = path.GetExt();

            _myWaveOut = new DirectSoundOut(device);
            try
            {
                _myWaveStream = _codecs.First(v => v.Extensions.Contains(cext)).CreateWaveStream(path);
            }
            catch
            {
                return(false);
            }
            if (_myWaveStream == null)
            {
                return(false);
            }
            if (_myWaveStream.WaveFormat.Channels == 2)
            {
                _myBalanceSampleProvider     = new BalanceSampleProvider(_myWaveStream.ToSampleProvider());
                _myVolumeSampleProvider      = new VolumeSampleProvider(_myBalanceSampleProvider);
                _myBalanceSampleProvider.Pan = (float)Balance;
            }
            else
            {
                _myVolumeSampleProvider = new VolumeSampleProvider(_myWaveStream.ToSampleProvider());
            }
            _myEqualizer = new Equalizer(_myVolumeSampleProvider, _equalizerBands)
            {
                Enabled = _enableEqualizer
            };
            _myWaveOut.Init(_myEqualizer);
            _myWaveOut.PlaybackStopped    += MyWaveOutOnPlaybackStopped;
            _myVolumeSampleProvider.Volume = (float)Volume;
            return(true);
        }
Ejemplo n.º 14
0
        public WaveStream Volume(WaveStream w, IMessage m, float VolumeFactor)
        {
            string filePath = $"Commands{Path.DirectorySeparatorChar}Edit{Path.DirectorySeparatorChar}volume.bin";

            lock (volumeLock)
            {
                VolumeSampleProvider pitch = new VolumeSampleProvider(w.ToSampleProvider())
                {
                    Volume = VolumeFactor
                };

                WaveFileWriter.CreateWaveFile16(filePath, pitch);
                return(new WaveFileReader(filePath));
            }
        }
 public override void ProcessPixels(RectangleI region)
 {
     LoadAudio();
     if (WaveStream == null)
     {
         return;
     }
     float[] samples = new float[SampleCount];
     WaveStream.CurrentTime = TimeSpan.FromSeconds(Time);
     WaveStream.ToSampleProvider().Read(samples, 0, samples.Length);
     WaveFormPath.MoveTo(0, DestImage.Height / 2 * (samples[0] + 1));
     for (int i = 0; i < samples.Length; i++)
     {
         WaveFormPath.LineTo((float)DestImage.Width / samples.Length * i, DestImage.Height / 2 * (samples[i] + 1));
     }
 }
Ejemplo n.º 16
0
        /*private void reverseToolStripMenuItem_Click(object sender, EventArgs e)
         * {
         *  if (reader == null)
         *      return;
         *  var data = GetDataOf16Bit2ChannelFile(reader);
         *  data = data.Reverse().ToArray();
         *
         *  //reader.Seek(0, System.IO.SeekOrigin.Begin);
         *  //byte[] result = new byte[data.Length * sizeof(short)];
         *  //Buffer.BlockCopy(data, 0, result, 0, result.Length);
         *
         *  MemoryStream mstream = new MemoryStream();
         *  BinaryWriter writer = new BinaryWriter(mstream);
         *  foreach (var item in data)
         *      writer.Write(item);
         *
         *  //reader.Write(result, 0, result.Length);
         *
         *  //reader = new RawSourceWaveStream(mstream, reader.WaveFormat);
         *
         *  var useTempo = radioButton1.Checked;
         *
         *  speedControl = new VarispeedSampleProvider(new RawSourceWaveStream(mstream, reader.WaveFormat).ToSampleProvider(), 100, new SoundTouchProfile(useTempo, false));
         *
         *  //speedControl = new VarispeedSampleProvider(new RawSourceWaveStream(mstream, reader2.WaveFormat).ToSampleProvider(), 100, new SoundTouchProfile(useTempo, false));
         *
         *  wout?.Stop();
         *  wout = new WaveOut();
         *  wout.Init(speedControl);
         *
         *  return;
         *  /*
         *  WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(reader2);
         *  WaveFileWriter waveFileWriter = new WaveFileWriter(reader2, waveStream.WaveFormat);
         *
         *  waveFileWriter.WriteAsync(result, 0, result.Length);
         *  waveFileWriter.Flush();
         *
         * }*/

        private void reverseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (reader == null)
            {
                return;
            }

            var data = GetDataOf16Bit2ChannelFile(reader);

            data = data.Reverse().ToArray();

            /*
             * reader.Seek(0, System.IO.SeekOrigin.Begin);
             * byte[] result = new byte[data.Length * sizeof(short)];
             * Buffer.BlockCopy(data, 0, result, 0, result.Length);
             */

            MemoryStream mstream = new MemoryStream();
            BinaryWriter writer  = new BinaryWriter(mstream);

            foreach (var item in data)
            {
                writer.Write(item);
            }

            var useTempo = radioButton1.Checked;

            reader       = new RawSourceWaveStream(mstream, reader.WaveFormat);
            speedControl = new VarispeedSampleProvider(reader.ToSampleProvider(), 100, new SoundTouchProfile(useTempo, false));

            var state = wout?.PlaybackState == PlaybackState.Playing;

            wout?.Stop();
            hScrollBar11.Value = 0;
            progressBar1.Value = 0;
            wout = new WaveOut();///
            wout.Init(speedControl);

            if (state)
            {
                wout.Play();
            }

            return;
        }
Ejemplo n.º 17
0
        public LoopSampleProvider(WaveStream sourceStream, int start, int end, int startSample = 0)
        {
            SourceStream = sourceStream;

            providers = new Queue <ISampleProvider>();

            this.start       = start;
            this.end         = end;
            this.startSample = startSample;
            this.loopLength  = (end - start) * 2;

            providers.Enqueue(new OffsetSampleProvider(SourceStream.ToSampleProvider())
            {
                TakeSamples = start * 2
            });

            currentProvider = providers.Dequeue();
        }
Ejemplo n.º 18
0
 private Audio(string path, float speed, bool repeat)
 {
     baseSpeed = speed;
     stream    = new AudioFileReader(path);
     if (repeat)
     {
         stream = new RepeatingStream(stream);
         ((RepeatingStream)stream).OnRepeat += (s, a) => this.OnRepeat?.Invoke(s, a);
     }
     speedControl = new VarispeedSampleProvider(stream.ToSampleProvider(), 10, new SoundTouchProfile(false, true));
     speedControl.PlaybackRate = baseSpeed;
     //player = new WaveOutEvent() { DesiredLatency = 120, NumberOfBuffers = 2 };
     //player = new DirectSoundOut(40);
     player = new DirectSoundOut(100);
     //PlaybackRate = 1;
     //player = new WaveOutEvent() { DesiredLatency = 200, NumberOfBuffers = 2 };
     player.Init(speedControl);
 }
Ejemplo n.º 19
0
        private static void ReadWaveStream(WaveStream audioStream)
        {
            // Convert
            WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(audioStream);

            float[] samplesPCM = new float[audioStream.Length];
            audioStream.ToSampleProvider().Read(samplesPCM, 0, (int)pcmStream.Length);

            // Store
            Data       = samplesPCM;
            length     = (int)audioStream.Length;
            waveFormat = audioStream.WaveFormat;

            // Cleanup
            audioStream.Dispose();

            // We has loaded
            isLoaded = true;
        }
Ejemplo n.º 20
0
        // constructor
        internal Audio(AudioType type, AudioFormat format, byte[] data, int device) : base(type, format, data, device)
        {
            playing.Value = false;

            waveOut.DeviceNumber     = device;
            waveOut.PlaybackStopped += OnPlaybackComplete;

            byteStream = new MemoryStream(data);
            if (Format == AudioFormat.AIFF)
            {
                waveStream = new AiffFileReader(byteStream);
            }
            else if (Format == AudioFormat.WAV)
            {
                waveStream = new WaveFileReader(byteStream);
            }
            else if (Format == AudioFormat.MP3)
            {
                waveStream = new Mp3FileReader(byteStream);
            }
            else if (Format == AudioFormat.Vorbis)
            {
                waveStream = new VorbisWaveReader(byteStream);
            }
            volumeProvider = new VolumeSampleProvider(waveStream.ToSampleProvider())
            {
                Volume = (float)Volume
            };

            if (waveStream.WaveFormat.Channels == 1)
            {
                panningProvider = new PanningSampleProvider(volumeProvider)
                {
                    Pan = (float)Pan
                };
                waveOut.Init(panningProvider);
            }
            else
            {
                waveOut.Init(volumeProvider);
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// This method uses NAudio to convert a mp3 file given as byte array to an AudioClip in .wav format.
        /// </summary>
        /// <param name="data">Data are the bytes of an mp3 file</param>
        public AudioClip CreateAudioClipFromMp3(byte[] data)
        {
            using (MemoryStream input = new MemoryStream(data))
                using (Mp3FileReader mp3Reader = new Mp3FileReader(input))
                    using (WaveStream reader = WaveFormatConversionStream.CreatePcmStream(mp3Reader))
                    {
                        WaveFormat format = reader.WaveFormat;
                        // Calculate buffer size for the AudioClip which seems half of the reader length maybe because of stereo?
                        float[]   buffer = new float[reader.Length / 2];
                        AudioClip clip   = AudioClip.Create("audio", buffer.Length, format.Channels, format.SampleRate, false);

                        reader.ToSampleProvider().Read(buffer, 0, buffer.Length);
                        clip.SetData(buffer, 0);
                        if (clip.LoadAudioData() && clip.loadState == AudioDataLoadState.Loaded)
                        {
                            return(clip);
                        }
                    }
            throw new UnableToParseAudioFormatException("Could not parse AudioClip from given mp3 data");
        }
Ejemplo n.º 22
0
        /// <summary>
        ///     Changes the file that is being read, setting up the new reader
        /// </summary>
        /// <param name="newFile"></param>
        private void ChangeFile(string newFile)
        {
            ErrorStrings.Clear();

            // Dispose of the old reader as needed
            try
            {
                if (Reader != null)
                {
                    Reader.Dispose();
                }
            } catch { }
            Reader  = null;
            Sampler = null;

            // Create the new reader
            var extension = Path.GetExtension(newFile).ToLower();

            switch (extension)
            {
            case ".wav":
                try
                {
                    Reader  = new WaveFileReader(newFile);
                    Sampler = Reader.ToSampleProvider();
                }
                catch (Exception ex)
                {
                    ErrorStrings.Add(ex.Message);
                }
                break;

            default:     // Unknown format
                ErrorStrings.Add($"The audio format {extension} is not supported.");
                break;
            }

            InvokeOnErrorStringsChanged();
        }
Ejemplo n.º 23
0
        private void OpenFile(string fileName)
        {
            try
            {
                var inputStream = new MediaFoundationReader(fileName);
                fileStream = inputStream;

                SampleAggregator = new SampleAggregator(fileStream.ToSampleProvider());
                SampleAggregator.NotificationCount  = inputStream.WaveFormat.SampleRate / 100;
                SampleAggregator.PerformFFT         = true;
                SampleAggregator.FftCalculated     += (s, a) => FftCalculated?.Invoke(this, a);
                SampleAggregator.MaximumCalculated += (s, a) => MaximumCalculated?.Invoke(this, a);
                Volume = 0.5f;
                playbackDevice.Volume = Volume;
                playbackDevice.Init(SampleAggregator);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Проблема открытия файла");
                CloseFile();
            }
        }
Ejemplo n.º 24
0
        public void Initialize(int audioDevice)
        {
            Dispose();

            waveOut = new WaveOutEvent();
            waveOut.DeviceNumber     = audioDevice;
            waveOut.PlaybackStopped += onPlaybackComplete;

            byteStream = new MemoryStream(_data);
            if (_format == AudioFormat.Aiff)
            {
                waveStream = new AiffFileReader(byteStream);
            }
            else if (_format == AudioFormat.Wav)
            {
                waveStream = new WaveFileReader(byteStream);
            }
            else if (_format == AudioFormat.Mp3)
            {
                waveStream = new Mp3FileReader(byteStream);
            }
            else if (_format == AudioFormat.Vorbis)
            {
                waveStream = new VorbisWaveReader(byteStream);
            }

            volumeProvider        = new VolumeSampleProvider(waveStream.ToSampleProvider());
            volumeProvider.Volume = (float)_volume;
            if (waveStream.WaveFormat.Channels == 1)
            {
                panningProvider     = new PanningSampleProvider(volumeProvider);
                panningProvider.Pan = (float)_pan;
                waveOut.Init(panningProvider);
            }
            else
            {
                waveOut.Init(volumeProvider);
            }
        }
Ejemplo n.º 25
0
        public static int TrimAudioFile(string inPath, string outPath, TimeSpan cutFromStart, TimeSpan cutFromEnd)
        {
            TimeSpan fadeSpan = new TimeSpan(0, 0, 0, 2, 470);

            if (Path.GetExtension(inPath) != ".mp3" && Path.GetExtension(inPath) != ".wav")
            {
                return(-1);
            }

            WaveStream ws;

            if (Path.GetExtension(inPath) == ".mp3")
            {
                ws = new Mp3FileReader(inPath);
            }
            else if (Path.GetExtension(inPath) == ".wav")
            {
                ws = new WaveFileReader(inPath);
            }
            else
            {
                return(-1);
            }

            try
            {
                //using (AudioFileReader audioReader = new AudioFileReader(inPath))
                using (WaveStream audioReader = ws)
                {
                    string temp_file = Path.GetTempFileName();

                    var sampleProvider = audioReader.ToSampleProvider();

                    var SampleRate = audioReader.WaveFormat.SampleRate;

                    var startPosition = (cutFromStart.TotalMilliseconds * SampleRate) / 1000;

                    var takeSpan = audioReader.TotalTime - cutFromStart - cutFromEnd;

                    var skipBeforeFade = takeSpan - fadeSpan;

                    sampleProvider = sampleProvider.Skip(cutFromStart);

                    sampleProvider = sampleProvider.Take(takeSpan);

                    //var fader = new FadeInOutSampleProvider(sampleProvider);
                    var fader = new DelayFadeOutSampleProvider(sampleProvider);

                    fader.BeginFadeOut(skipBeforeFade.TotalMilliseconds, fadeSpan.TotalMilliseconds);

                    //fader.BeginFadeOut(fadeSpan.TotalMilliseconds);


                    var wave = new SampleToWaveProvider(fader);

                    //WaveFileWriter.CreateWaveFile(outPath, wave);


                    using (WaveFileWriter writer = new WaveFileWriter(temp_file, audioReader.WaveFormat))
                    {
                        int     read    = 0;
                        float[] fBuffer = new float[64 * 1024];
                        do
                        {
                            read = fader.Read(fBuffer, 0, 64 * 1024);
                            if (read > 0)
                            {
                                writer.WriteSamples(fBuffer, 0, read);
                            }

                            //read = wave.Read(fBuffer, 0, 1024);
                            //if (read > 0)
                            //{
                            //    writer.Write(fBuffer, 0, read);
                            //}
                        } while (read > 0);
                    }

                    Console.Write($"Writing file: {Path.GetFileName(outPath)}.....");
                    File.Copy(temp_file, outPath);
                    Console.WriteLine($"Done.");
                    File.Delete(temp_file);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine();
                Console.WriteLine($"Error: {e.Message}");
                return(-1);
            }

            return(1);
        }
Ejemplo n.º 26
0
    private void GetWaveform(WaveStream reader, int width, int height, int peakCount, Action <Texture2D> callback)
    {
        int           bytesPerSample  = reader.WaveFormat.BitsPerSample / 8;
        var           samples         = reader.Length / bytesPerSample;
        var           samplesPerPixel = (int)(samples / width);
        IPeakProvider peakProvider    = new RmsPeakProvider(1);

        peakProvider.Init(reader.ToSampleProvider(), samplesPerPixel);
        int       p           = 0;
        var       currentPeak = peakProvider.GetNextPeak();
        int       peakNum     = 0;
        Texture2D texture     = new Texture2D(waveFormWidth, waveFormHeight);

        for (int x = 0; x < waveFormWidth; x++)
        {
            for (int y = 0; y < waveFormHeight; y++)
            {
                texture.SetPixel(x, y, Color.clear);
            }
        }
        float[] peakSizes   = new float[peakCount];
        float   peakSize    = 0f;
        float   maxPeakSize = 0f;

        while (p < width)
        {
            peakSize += Mathf.Abs(currentPeak.Max) + Mathf.Abs(currentPeak.Min);
            if (p % (peakWidth + spaceWidth) == 0)
            {
                peakSizes[peakNum] = peakSize;
                maxPeakSize        = maxPeakSize < peakSize ? peakSize : maxPeakSize;
                peakSize           = 0;
                peakNum++;
            }
            var nextPeak = peakProvider.GetNextPeak();
            currentPeak = nextPeak;
            p++;
        }
        peakNum = 0;
        p       = 0;
        float k = waveFormHeight / (2 * maxPeakSize + peakWidth);

        while (p < width)
        {
            peakSize = peakSizes.Length <= peakNum ? 0f : peakSizes[peakNum];
            peakSize = peakSize * k;
            var pos = p % (peakWidth + spaceWidth);
            if (pos > spaceWidth)
            {
                int pX = pos - spaceWidth;
                pX = pX <= peakWidth / 2 ? pX : peakWidth - pX;
                var pS = peakSize + Mathf.Sqrt(3 / 4 * peakWidth - 2 * pX * pX + 2 * pX * peakWidth);
                for (int y = 0; y < waveFormHeight; y++)
                {
                    if (Mathf.Abs(y - waveFormHeight / 2) < pS)
                    {
                        texture.SetPixel(p, y, new Color(1, 1, 1, pS - Mathf.Abs(y - waveFormHeight / 2)));
                    }
                }
            }
            if ((p + spaceWidth) % (spaceWidth + peakWidth) == 0)
            {
                peakNum++;
            }
            p++;
        }
        texture.Apply();
        texture.filterMode = FilterMode.Bilinear;
        callback?.Invoke(texture);
    }
Ejemplo n.º 27
0
        public WaveStream Pitch(WaveStream w, IMessage m, float PitchFactor)
        {
            string filePath = $"Commands{Path.DirectorySeparatorChar}Edit{Path.DirectorySeparatorChar}pitch.bin";

            lock (pitchLock)
            {
                SmbPitchShiftingSampleProvider pitch = new SmbPitchShiftingSampleProvider(w.ToSampleProvider())
                {
                    PitchFactor = PitchFactor
                };

                WaveFileWriter.CreateWaveFile16(filePath, pitch);
                return(new WaveFileReader(filePath));
            }
        }
Ejemplo n.º 28
0
 public RepeatedStream(WaveStream waveStream)
 {
     _waveStream = waveStream;
     _provider   = waveStream.ToSampleProvider();
 }
Ejemplo n.º 29
0
        private void Editbtn_Click(object sender, EventArgs e)
        {
            if (reader == null)
            {
                return;
            }
            try
            {
                float volume;
                if (!float.TryParse(Volumetb.Text, out volume))
                {
                    throw new Exception("volume value not valid");
                }

                var data = GetDataOf16Bit2ChannelFile(reader);
                volume /= 100;
                for (int i = 0; i < data.Length; i++)
                {
                    data[i] = (short)Math.Max(Math.Min(data[i] * volume, (int)short.MaxValue), (int)short.MinValue);
                }

                MemoryStream mstream = new MemoryStream();
                BinaryWriter writer  = new BinaryWriter(mstream);
                foreach (var item in data)
                {
                    writer.Write(item);
                }

                var useTempo = radioButton1.Checked;
                reader       = new RawSourceWaveStream(mstream, reader.WaveFormat);
                speedControl = new VarispeedSampleProvider(reader.ToSampleProvider(), 100, new SoundTouchProfile(useTempo, false));

                var state = wout?.PlaybackState == PlaybackState.Playing;
                wout?.Stop();
                hScrollBar11.Value = 0;
                progressBar1.Value = 0;
                wout = new WaveOut();///
                wout.Init(speedControl);

                if (state)
                {
                    wout.Play();
                }

                return;

                /*var state = wout.PlaybackState == PlaybackState.Playing;
                 * wout?.Stop();
                 * wout = new WaveOut();///
                 * wout.Init(speedControl);
                 *
                 * if (state)
                 *  wout.Play();
                 * //wout.Init(reader2);*/
                /*
                 * var data = GetDataOf16Bit2ChannelFile(reader);
                 * //short[] newData = new short[data.Length];
                 * for (int i = 0; i < data.Length; i++)
                 * {
                 *  data[i] *= volume;
                 * }
                 *
                 * MemoryStream mstream = new MemoryStream();
                 * BinaryWriter writer = new BinaryWriter(mstream);
                 * foreach (var item in data)
                 *  writer.Write(item);
                 *
                 * var useTempo = radioButton1.Checked;
                 * reader = new RawSourceWaveStream(mstream, reader.WaveFormat);
                 * speedControl = new VarispeedSampleProvider(reader.ToSampleProvider(), 100, new SoundTouchProfile(useTempo, false));
                 *
                 * var state = wout?.PlaybackState == PlaybackState.Playing;
                 * wout?.Stop();
                 * hScrollBar1.Value = 0;
                 * progressBar1.Value = 0;
                 * wout = new WaveOut();///
                 * wout.Init(speedControl);
                 *
                 * if (state)
                 *  wout.Play();
                 *
                 * return;*/
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }