Ejemplo n.º 1
0
        /// <summary>
        /// Generates the PC speaker waveform.
        /// </summary>
        private async Task GenerateWaveformAsync()
        {
            using var player = Audio.CreatePlayer();

            FillWithSilence(player);

            var  buffer         = new byte[4096];
            var  writeBuffer    = buffer;
            bool expandToStereo = false;

            if (player.Format.Channels == 2)
            {
                writeBuffer    = new byte[buffer.Length * 2];
                expandToStereo = true;
            }

            player.BeginPlayback();

            int idleCount = 0;

            while (idleCount < 10000)
            {
                if (this.queuedNotes.TryDequeue(out var note))
                {
                    int samples = GenerateSquareWave(buffer, note.Period);
                    int periods = note.PeriodCount;

                    if (expandToStereo)
                    {
                        ChannelAdapter.MonoToStereo(buffer.AsSpan(0, samples), writeBuffer.AsSpan(0, samples * 2));
                        samples *= 2;
                    }

                    while (periods > 0)
                    {
                        Audio.WriteFullBuffer(player, writeBuffer.AsSpan(0, samples));
                        periods--;
                    }

                    GenerateSilence(buffer);
                    idleCount = 0;
                }
                else
                {
                    while (player.WriteData(buffer) > 0)
                    {
                    }

                    await Task.Delay(5, this.cancelGenerateWaveform.Token);

                    idleCount++;
                }

                this.cancelGenerateWaveform.Token.ThrowIfCancellationRequested();
            }
        }
Ejemplo n.º 2
0
        private void GenerateWaveforms()
        {
            var buffer = new float[1024];

            float[] playBuffer;

            bool expandToStereo = this.audioPlayer.Format.Channels == 2;

            if (expandToStereo)
            {
                playBuffer = new float[buffer.Length * 2];
            }
            else
            {
                playBuffer = buffer;
            }

            this.audioPlayer.BeginPlayback();
            fillBuffer();
            while (!endThread)
            {
                Audio.WriteFullBuffer(this.audioPlayer, playBuffer);
                fillBuffer();
            }

            this.audioPlayer.StopPlayback();

            void fillBuffer()
            {
                this.synth.GetData(buffer);
                if (expandToStereo)
                {
                    ChannelAdapter.MonoToStereo(buffer.AsSpan(), playBuffer.AsSpan());
                }
            }
        }