public byte[] GenerateTone(Envelope envelope, Sweep sweep) { double timeResolution = 1.0 / 128.0; int timeSteps = 0; byte[] result = new byte[LengthInSamples(2f)]; byte[] outBuffer; double frequency = CalcFreq(sweep.Frequency); int resultIndex = 0; while (true) { outBuffer = GenerateTone(frequency, timeResolution, AMPLITUDE_STEPS * envelope.InitialVolume); timeSteps++; if (envelope.Sweep > 0 && timeSteps % (envelope.Sweep * 2) == 0) { if (envelope.Increasing) { envelope.InitialVolume++; } else { envelope.InitialVolume--; } } if (sweep.SweepEnable() && timeSteps % sweep.SweepTime == 0) { sweep.SweepSet(); frequency = CalcFreq(sweep.Frequency); } if (resultIndex + outBuffer.Length > result.Length) { Array.Copy(outBuffer, 0, result, resultIndex, result.Length - resultIndex); return(result); //array is full, return it. } Array.Copy(outBuffer, 0, result, resultIndex, outBuffer.Length); resultIndex += outBuffer.Length; if ((envelope.Increasing && envelope.InitialVolume == 0xf) || (!envelope.Increasing && envelope.InitialVolume == 0x00) || sweep.Frequency > 2047) { return(result); } } }