예제 #1
0
        public void Play(long x = 0)
        {
            if (reader2 == null)
            {
                return;
            }

            if (wout?.PlaybackState == PlaybackState.Playing)
            {
                return;
            }

            long x2 = x * Program.Editer.GetLength() / 1000;

            if (x2 > reader2.Length)
            {
                x = x2 = 0;
            }
            reader2.Seek(x2, System.IO.SeekOrigin.Begin);
            var useTempo = true;//radioButton1.Checked;

            speedControl = new VarispeedSampleProvider(this.reader2.ToSampleProvider(), 100, new SoundTouchProfile(useTempo, false));

            wout?.Stop();
            wout?.Dispose();
            //hScrollBar11.Value = 0;
            //progressBar1.Value = 0;
            MainUI.SeekBar((int)x);
            wout = new WaveOut();
            wout.Init(speedControl);
            wout.Volume = Volume;
            wout.Play();
        }
예제 #2
0
        public short[] GetDataOf16Bit2ChannelFile(WaveStream reader)
        {
            reader.Seek(0, System.IO.SeekOrigin.Begin);
            byte[] data2 = new byte[reader.Length];
            reader.Read(data2, 0, data2.Length);

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

            return(res2);

            /*
             * reader.Seek(0, System.IO.SeekOrigin.Begin);
             * byte[] data = new byte[reader.Length];
             * reader.Read(data, 0, data.Length);
             * short[] res = new short[data.Length / 2];
             * for (int i = 0; i < data.Length; i += 2)
             *  res[i / 2] = BitConverter.ToInt16(data, i);
             *
             *
             * // do we have the same sequence?
             * Debug.WriteLine(res.SequenceEqual(res2));    // True
             *
             * return res;
             */
        }
예제 #3
0
        private void playToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (reader == null)
            {
                return;
            }

            reader.Seek(0, System.IO.SeekOrigin.Begin);

            wout?.Dispose();
            wout = new WaveOut();
            wout.Init(speedControl);
            wout.Play();

            timer1.Enabled = true;
        }
예제 #4
0
        private async void Play()
        {
            if (reader == null)
            {
                return;
            }

            if (player == null)
            {
                // Exclusive mode - fails with a weird buffer alignment error

                //player = new MediaElementOut(MediaElement);
                player = new WasapiOutRT(AudioClientShareMode.Shared, 200);

                player.PlaybackStopped += PlayerOnPlaybackStopped;
            }

            if (player.PlaybackState != PlaybackState.Playing)
            {
                reader.Seek(0, SeekOrigin.Begin);
                await player.Init(reader);

                player.Play();
                StopCommand.IsEnabled  = true;
                PauseCommand.IsEnabled = true;
            }
        }
예제 #5
0
 public void SetPos(int time)
 {
     if (stream == null)
     {
         return;
     }
     stream.Seek(time * stream.WaveFormat.AverageBytesPerSecond, SeekOrigin.Begin);
 }
예제 #6
0
        /// <summary>
        ///     Reproduce la cancion anterior de la cola o reinicia la reproduccion de la actual si el tiempo de reproduccion
        ///     es menor o igual a 10 segundos
        /// </summary>
        public void ReproducirCancionAnterior()
        {
            try
            {
                if (_blockAlignedStream.CurrentTime.TotalSeconds <= 10)
                {
                    switch (_colaDeReproduccion.ObtenerTipoDeCancionAnterior())
                    {
                    case Cola.TipoCancionAReproducir.Cancion:
                        var cancionAnterior = _colaDeReproduccion.ObtenerCancion(true);
                        if (cancionAnterior != null)
                        {
                            EmpezarAReproducirCancion(cancionAnterior);
                        }
                        break;

                    case Cola.TipoCancionAReproducir.CancionPersonal:
                        var cancionPersonalAnterior = _colaDeReproduccion.ObtenerCancionPersonal(true);
                        if (cancionPersonalAnterior != null)
                        {
                            EmpezarAReproducirCancionPersonal(cancionPersonalAnterior);
                        }
                        break;

                    case Cola.TipoCancionAReproducir.CancionSinConexion:
                        var cancionSinConexionAnteriror = _colaDeReproduccion.ObtenerCancionSinConexion(true);
                        if (cancionSinConexionAnteriror != null)
                        {
                            EmpezarAReproducirCancionSinConexion(cancionSinConexionAnteriror);
                        }
                        break;
                    }
                }
                else
                {
                    if (_blockAlignedStream != null)
                    {
                        _blockAlignedStream.Seek(0, SeekOrigin.Begin);
                        OnAvanceCancion?.Invoke(0);
                        if (_estadoReproductor == EstadoReproductor.Detenido)
                        {
                            _waveOutEvent.Play();
                            if (_estadoReproductor == EstadoReproductor.Detenido ||
                                _estadoReproductor == EstadoReproductor.Pausado)
                            {
                                _seguidorDeEventosDelReproductor.Start();
                                _estadoReproductor = EstadoReproductor.Reproduciendo;
                            }

                            OnCambioEstadoReproduccion?.Invoke(true);
                        }
                    }
                }
            }
            catch (NullReferenceException)
            {
            }
        }
예제 #7
0
 private void SeekToSecondInCaseIfRequired(int startAtSecond, WaveStream stream)
 {
     if (startAtSecond > 0)
     {
         int actualSampleRate = stream.WaveFormat.SampleRate;
         int bitsPerSample    = stream.WaveFormat.BitsPerSample;
         stream.Seek(actualSampleRate * bitsPerSample / 8 * startAtSecond, System.IO.SeekOrigin.Begin);
     }
 }
 private void SeekToSecondInCaseIfRequired(int startAtSecond, WaveStream stream)
 {
     if (startAtSecond > 0)
     {
         int actualSampleRate = stream.WaveFormat.SampleRate;
         int bitsPerSample = stream.WaveFormat.BitsPerSample;
         stream.Seek(actualSampleRate * bitsPerSample / 8 * startAtSecond, System.IO.SeekOrigin.Begin);
     }
 }
예제 #9
0
        /// <summary>
        /// Main update event handler.
        /// </summary>
        /// <param name="sender">Sender of the event.</param>
        /// <param name="e">Event arguments.</param>
        private void UpdateBattery(object sender, EventArgs e)
        {
            //Icon caption.
            if (_pow.BatteryLifeRemaining != -1)
            {
                var timeSpan      = TimeSpan.FromSeconds(_pow.BatteryLifeRemaining);
                var remainingTime = string.Format("{0:D2}h {1:D2}m", timeSpan.Hours, timeSpan.Minutes);
                _trayIcon.Text = "Remaining: " + remainingTime + ".";
            }
            else
            {
                _reminderDisabledUntilCharging            = false;
                _reminderDisableUntilChargingItem.Checked = false;

                if (_pow.PowerLineStatus != 0)
                {
                    _trayIcon.Text = "Charging.";
                }
                else
                {
                    _trayIcon.Text = "Calculating remaining time...";
                }
            }
            //Icon caption.

            _percentageCurrent = (int)Math.Round(_pow.BatteryLifePercent * 100.0);

            if (_percentagePrev != _percentageCurrent)
            {
                //Updating icon.
                if (_trayIcon.Icon != null)
                {
                    _trayIcon.Icon.Dispose();
                }

                Image image = RenderIcon(_percentageCurrent);
                _trayIcon.Icon = ToIcon(image);
                image.Dispose();
            }

            _percentagePrev = _percentageCurrent;

            // Playing reminder sound.
            if (_reminderEnabled &&
                !_reminderDisabledUntilShutdown &&
                !_reminderDisabledUntilCharging &&
                _percentageCurrent <= _reminderTriggerValue &&
                _pow.PowerLineStatus == 0
                )
            {
                _waveStream.Seek(0, SeekOrigin.Begin);
                _soundPlayer.Play();
            }
            // Playing reminder sound.
        }
예제 #10
0
 public void SetPos(int time)
 {
     sync.InvokeIfRequired((Action) delegate
     {
         if (stream == null)
         {
             return;
         }
         stream.Seek(time * stream.WaveFormat.AverageBytesPerSecond, SeekOrigin.Begin);
     });
 }
예제 #11
0
 short[] GetDataOf16Bit2ChannelFile(WaveStream reader)
 {
     reader.Seek(0, System.IO.SeekOrigin.Begin);
     byte[] data = new byte[reader.Length];
     reader.Read(data, 0, data.Length);
     short[] res = new short[data.Length / 2];
     for (int i = 0; i < data.Length; i += 2)
     {
         res[i / 2] = BitConverter.ToInt16(data, i);
     }
     return(res);
 }
예제 #12
0
 private void timer1_Tick(object sender, EventArgs e)
 {
     trackBar1.Value = (int)Math.Ceiling(Stream.CurrentTime.TotalSeconds);
     if (Stream.CurrentTime == Stream.TotalTime)
     {
         Output.Stop();
         trackBar1.Value = 0;
         Stream.Seek(0, SeekOrigin.Begin);
         IsPlaying = false;
         timer1.Stop();
         button1.Image = Resource.control;
     }
 }
        public virtual bool AppendStereo(WaveStream stream, SpeechAudioChannel channel)
        {
            if (IsSessionOpen)
            {
                if (stream.CanSeek)
                {
                    stream.Seek(0, SeekOrigin.Begin);
                }

                Logger?.LogDebug("SpeechEnrollerBase.AppendStereo(): In-Channel: " + channel);
                Logger?.LogDebug("SpeechEnrollerBase.AppendStereo(): In-Length: " + stream.Length);
                Logger?.LogDebug("SpeechEnrollerBase.AppendStereo(): In-WaveFormat: " + stream.WaveFormat);

                SpeechAudio speechAudio;
                if (Codec == WaveFormatEncoding.Pcm)
                {
                    speechAudio = new SpeechAudio(stream, new WaveFormat(8000, 16, 2), channel);
                }
                else
                {
                    return(false);
                }

                Logger?.LogDebug("SpeechEnrollerBase.AppendStereo(): Append-Length: " + speechAudio.Stream.Length);
                Logger?.LogDebug("SpeechEnrollerBase.AppendStereo(): Append-WaveFormat: " + speechAudio.Stream.WaveFormat);

                speechAudio.FileName = BuildAudioName();

                switch (channel)
                {
                case SpeechAudioChannel.Mono:
                    Content.Add("data", speechAudio);
                    break;

                case SpeechAudioChannel.StereoLeft:
                    Content.Add("left", speechAudio);
                    break;

                case SpeechAudioChannel.StereoRight:
                    Content.Add("right", speechAudio);
                    break;
                }

                TotalSnippetsSent++;
                TotalAudioBytesSent += speechAudio.Stream.Length;

                return(true);
            }
            return(false);
        }
예제 #14
0
        public BeatReader(WaveStream wave, bool keepAlive, int fftLength = 1024)
        {
            if (!IsPowerOfTwo(fftLength))
            {
                throw new ArgumentException("FFT Length must be a power of two");
            }
            beats            = new List <Beat>();
            this.wave        = wave;
            analyzer         = new SpectrumAnalyzer(fftLength);
            sampleAggregator = new SampleAggregator(fftLength);

            sampleAggregator.FftCalculated += new EventHandler <FftEventArgs>(FftCalculated);
            sampleAggregator.PerformFFT     = true;

            SongDuration = wave.TotalTime;
            byte[] buffer = new byte[fftLength];
            int    bytes  = 1;
            int    index  = 0;

            beatThread = new Thread(new ThreadStart(() =>
            {
                bool nullRef = false;
                while (wave.CanRead && bytes > 0 && wave.CurrentTime < wave.TotalTime && !nullRef)
                {
                    try
                    {
                        TimeSpan time = wave.CurrentTime;
                        index++;
                        bytes = wave.Read(buffer, 0, fftLength);
                        wave.Seek(index * fftLength, System.IO.SeekOrigin.Begin);
                        totalBytes       += bytes;
                        WaveInEventArgs e = new WaveInEventArgs(buffer, bytes);
                        OnDataAvailable(null, e, time);
                    }
                    catch (NullReferenceException)
                    {
                        //thread has been killed
                        nullRef = true;
                    }
                    catch (ObjectDisposedException)
                    {
                        //wave has been disposed
                        nullRef = true;
                    }
                }
            }));
            beatThread.Start();
        }
예제 #15
0
            public int Read(float[] buffer, int offset, int count)
            {
                int read = 0;

                while (LoopCount > 0)
                {
                    read += _provider.Read(buffer, offset + read, count - read);
                    if (read >= count)
                    {
                        return(read);
                    }

                    LoopCount--;
                    _waveStream.Seek(0, SeekOrigin.Begin);
                }
                return(read);
            }
예제 #16
0
        /// <summary>
        /// Initializes a new WaveOutAudioSource class.
        /// </summary>
        /// <param name="waveStream">The WaveStream.</param>
        internal WaveOutAudioSource(WaveStream waveStream)
        {
            waveStream.Seek(0, SeekOrigin.Begin);
            WaveData = new byte[waveStream.Length];
            waveStream.Read(WaveData, 0, WaveData.Length);
            waveStream.Close();
            WaveFormat = waveStream.Format;

            if (WaveFormat.Channels == 1) //try to convert to stereo for full audiomixer support
            {
                try
                {
                    new MonoToStereoConverter().ConvertAudioData(WaveData, ref WaveFormat);
                }
                catch (NotSupportedException)
                {
                }
            }
        }
예제 #17
0
        public void StandardizBitsPerSample()
        {
            if (reader == null)
            {
                return;
            }
            if (reader.WaveFormat.BitsPerSample == Program.Editer.BitsPerSample)
            {
                return;
            }

            reader.Seek(0, System.IO.SeekOrigin.Begin);
            byte[] data = new byte[reader.Length];
            reader.Read(data, 0, data.Length);

            int bps = reader.WaveFormat.BitsPerSample;

            short[] res = new short[data.Length / (bps / 8)];

            for (int i = 0, j = 0; i < data.Length; i += bps, j++)
            {
                var  b     = data.Skip(i).Take(bps).ToArray();
                long value = 0;
                for (int k = 0; k < b.Length; k++)
                {
                    value += ((long)b[k] & 0xffL) << (8 * k);
                }
                //if (bps < Program.Editer.BitsPerSample)
                //    res[j] = (short)value;
                //else
                res[j] = (short)(value * Program.Editer.BitsPerSample / bps);
            }

            for (int i = 0; i < data.Length; i += 2)
            {
                res[i / 2] = BitConverter.ToInt16(data, i);
            }

            var byteArray = new byte[res.Length * 2];

            Buffer.BlockCopy(res, 0, byteArray, 0, byteArray.Length);
            reader = new RawSourceWaveStream(byteArray, 0, byteArray.Length, new WaveFormat(reader.WaveFormat.SampleRate, Program.Editer.BitsPerSample, reader.WaveFormat.Channels));
        }
예제 #18
0
        /// <summary>
        /// Initializes a new WaveOutAudioSource class.
        /// </summary>
        /// <param name="waveStream">The WaveStream.</param>
        internal WaveOutAudioSource(WaveStream waveStream)
        {
            waveStream.Seek(0, SeekOrigin.Begin);
            WaveData = new byte[waveStream.Length];
            waveStream.Read(WaveData, 0, WaveData.Length);
            waveStream.Close();
            WaveFormat = waveStream.Format;

            if (WaveFormat.Channels == 1) //try to convert to stereo for full audiomixer support
            {
                try
                {
                    new MonoToStereoConverter().ConvertAudioData(WaveData, ref WaveFormat);
                }
                catch (NotSupportedException)
                {
                }
            }
        }
        public virtual bool Append(WaveStream stream)
        {
            if (IsSessionOpen)
            {
                if (stream.CanSeek)
                {
                    stream.Seek(0, SeekOrigin.Begin);
                }

                Logger?.LogDebug("SpeechEnrollerBase.Append(): In-Length: " + stream.Length);
                Logger?.LogDebug("SpeechEnrollerBase.Append(): In-WaveFormat: " + stream.WaveFormat);

                SpeechAudio speechAudio;
                if (Codec == WaveFormatEncoding.ALaw)
                {
                    speechAudio = new SpeechAudio(stream, WaveFormat.CreateALawFormat(8000, 1));
                }
                else if (Codec == WaveFormatEncoding.Pcm)
                {
                    speechAudio = new SpeechAudio(stream, new WaveFormat(8000, 16, 1));
                }
                else
                {
                    return(false);
                }

                Logger?.LogDebug("SpeechEnrollerBase.Append(): Append-Length: " + speechAudio.Stream.Length);
                Logger?.LogDebug("SpeechEnrollerBase.Append(): Append-WaveFormat: " + speechAudio.Stream.WaveFormat);

                speechAudio.FileName = BuildAudioName();

                Content.Add("data", speechAudio);

                TotalSnippetsSent++;
                TotalAudioBytesSent += speechAudio.Stream.Length;

                return(true);
            }
            return(false);
        }
예제 #20
0
 public long SetPosition(long value)
 {
     return(reader.Seek(value, SeekOrigin.Begin));
 }
예제 #21
0
 /// <summary>
 /// Decodes the Wave stream into a Signal object.
 /// </summary>
 ///
 /// <param name="index">Audio frame index to start decoding.</param>
 /// <param name="frames">The number of frames to decode.</param>
 ///
 /// <returns>Returns the decoded signal.</returns>
 ///
 public Signal Decode(int index, int frames)
 {
     waveStream.Seek(index * channels, SeekOrigin.Begin);
     return(Decode(frames));
 }
예제 #22
0
    private BitmapSource _Draw_WPF(CancellationToken ct, double height, double width, double offsetStart = 0, double offsetEnd = 0)
    {
        if (offsetEnd == 0)
        {
            offsetEnd = height;
        }
        isDrawing = true;
        reader.Seek(0, SeekOrigin.Begin);
        int            bytesPerSample = reader.WaveFormat.BitsPerSample / 8 * reader.WaveFormat.Channels;
        DrawingVisual  dv             = new DrawingVisual();
        DrawingContext dc             = dv.RenderOpen();
        Pen            bluePen        = new Pen(new SolidColorBrush(Constants.Editor.Waveform.ColourWPF), Constants.Editor.Waveform.ThicknessWPF);

        bluePen.Freeze();

        // TODO fix floating point rounding errors here
        int bytesPerPixel = (int)(reader.Length / height);
        int bytesRead     = 0;

        byte[] waveData = new byte[bytesPerPixel];
        // draw each pixel of height
        for (int y = 0; y <= height; y++)
        {
            bytesRead = reader.Read(waveData, 0, bytesPerPixel);

            if (bytesRead == 0)
            {
                break;
            }
            if (y < offsetStart)
            {
                continue;
            }
            if (y > offsetEnd)
            {
                break;
            }
            float low  = 0;
            float high = 0;
            // read all samples for this pixel and take the extreme values
            for (int n = 0; n < bytesRead; n += bytesPerSample)
            {
                float sample = BitConverter.ToSingle(waveData, n);
                if (sample < low)
                {
                    low = sample;
                }
                if (sample > high)
                {
                    high = sample;
                }
                if (ct.IsCancellationRequested)
                {
                    isDrawing = false;
                    return(null);
                }
            }
            float lowPercent  = (low + 1) / 2;
            float highPercent = (high + 1) / 2;
            float lowValue    = (float)width * lowPercent;
            float highValue   = (float)width * highPercent;
            dc.DrawLine(bluePen, new Point(lowValue, (int)(offsetEnd - offsetStart - y)), new Point(highValue, (int)(offsetEnd - offsetStart - y)));
        }
        dc.Close();
        RenderTargetBitmap bmp = new RenderTargetBitmap((int)width, (int)(offsetEnd - offsetStart), 96, 96, PixelFormats.Pbgra32);

        bmp.Render(dv);
        bmp.Freeze();

        //Trace.WriteLine($"{reader.Position}");
        isDrawing = false;
        // program crashes with UCEERR_RENDERTHREADFAILURE if this isnt converted to a BitmapImage
        // https://github.com/dotnet/wpf/issues/3100
        RenderTargetToDisk(bmp);
        return(RenderTargetToImage(bmp));
    }