I have to design a program that plays sounds (from WAV files). I have to create a wav and play it. Once it finishes I have to change the contents of that wave file and play it again. It is like playing a wave file that is constantly changing. I thought of creating a stream but the problem is when i edit that stream (using ms.Postion and ms.WriteByte), an error occurs saying that "the wave header file is corrupt". The following is my code:
MemoryStream ms = new MemoryStream(Sample1);
SoundPlayer myPlayer = new SoundPlayer(ms);
myPlayer.Play(); //Wav file plays
for (int x = 0; x < 50; x++)
{
ms.Position = 44 + x;
ms.WriteByte(10);
}
myPlayer.Stop();
myPlayer.Play(); //Header file corrupt
Is there maybe another way I can loop a stream, and change its contents while it is playing. For example, the stream is looping Sound1 and whenever a button is pressed, the stream's content is changed to play Sound2.
Thank you!
I've tried to do the same thing you want, also failed. It seems that the
SoundPlayer
class copies the contents to either an internal buffer or directly reserves the sound card memory. When you call play for the first time it also callsLoad
to do the previously mentioned thing. Re-assigning the same stream to the class didn't help me, calling Load to force it to reload the contents also failed. I don't know exactly how they implemented this class but I think that you will need to have twoSoundPlayer
classes and (very likely
) you can use them with the same stream (although I think you can't play them both at the same time, not because of the shared stream but because of the other issues). If the generated wave is not to big you could also try to use a singleSoundPlayer
class with two memory streams (I think that if you assign a different memory stream to the class that it should force a reload). I haven't tested any of the proposed solutions. Just remember to rewind the stream before passing it to theSoundPlayer
class (I suspect that was the original problem of the header corrupt problem). I haven't tested this but I think that it should work. Changing the contents of theSample1
isn't supposed to have any effect on the memory stream at least in my knowledgeIf the above fails, or just because you are a performance freak like me, I would suggest that you use DirectSound (part of managed DirectX) if available or import and use native wave functions and structures located in winmm.dll to achieve the thing you want.
Sorry about the vague answer but I just don't have the time to test it thoroughly.