Hello Everyone!
i have created a little app that can emulate an electric piano(but it only will play sine waves) i have based my app on
this article
now i am using the play to stream part of the demo. what this does is it writes the entire wave file of what ever note i specify into memory and then plays it back using the System.Media.SoundPlayer class.
but the problem is that every time i click the button in the form to play a note, the memory usage (i am watching this happen on task manager) increases by a few hundred KBs
i think this is due to the fact that i am storing a lot of data into memory but i am never deleting it. so my question is how to i clear the contents of a MemoryStream?
here is what i have so far:
this is executed on a separate thread
private void Operation()
{
MemoryStream stream = new MemoryStream();
PlayNote(stream, 180, 5000, false, NoteToPlayFreq, 1, 5000);
stream.Position = 0;
SoundPlayer player = new SoundPlayer(stream);
player.PlaySync();
stream.Dispose();
NoteCompletedEvent();
}
now the PlayNote method is this:
public void PlayNote(Stream output, double tempo, short defaultVolume, bool closeUnderlyingStream, float frequency, double length, short volume)
{
this._tempo = tempo;
_writer = new WaveWriter16Bit(output, 44100, false, closeUnderlyingStream);
_defaultVolume = defaultVolume;
if (volume < 0)
throw new ArgumentOutOfRangeException("volume", "Volume must be greater than or equal to zero.");
double samplesPerCycle = _writer.SampleRate / frequency;
int samplesForNote = (int)(_writer.SampleRate * length * 60 / Tempo);
Sample16Bit sample = new Sample16Bit();
for (int currentSample = 0; currentSample < samplesForNote; currentSample++)
{
bool endOfStream = true;
if (_writer.CurrentSample < _writer.NumberOfSamples)
{
sample = _writer.Read();
endOfStream = false;
}
else
sample.LeftChannel = 0;
int distanceFromEnd = samplesForNote - currentSample;
short finalVolume = distanceFromEnd < 1000 ? ((short)(volume * distanceFromEnd / 1000)) : volume;
double sampleValue = Math.Sin(currentSample / samplesPerCycle * 2 * Math.PI) * finalVolume + sample.LeftChannel;
if (sampleValue > short.MaxValue)
sampleValue = short.MaxValue;
else if (sampleValue < short.MinValue)
sampleValue = short.MinValue;
sample.LeftChannel = (short)(sampleValue);
if (endOfStream == false)
_writer.CurrentSample--;
_writer.Write(sample);
}
if (_writer != null)
_writer.Close();
}
i figure that if i played a long song(in excess of a few thousand button clicks) then my memory usage for this app would be through the roof.
so what am i doing wrong?
thanks for your help in advance,
MasterCodeon