Play from a memory stream(which doesn't contain wav headers) in WPF

1.5k views Asked by At

I try to concatenate some data in different durations but same sample rate. I concatenate the data with MemoryStream.CopyTo(memoryStream) method.

Is there any way to play a data from a memory stream which don't have a wav header in the start?

And if not, is there any way to append a wav headers to to start after the stream was appended?

(I want to avoid generating a file in the disk..)

2

There are 2 answers

0
Mark Heath On BEST ANSWER

To do this with NAudio, just use a RawSourceWaveStream and pass in the MemoryStream containing the raw concatenated audio to its constructor. You'll also need to explicitly specify that the WaveFormat is.

memoryStream = ... // construct your audio
memoryStream.Position = 0; // rewind to beginning
var rs = new RawSourceWaveStream(memoryStream, new WaveFormat(sampleRate, 16, 1));
4
cyberj0g On

You can write header to your stream, then play the WAV with SoundPlayer.

    //your wav streams
    MemoryStream wavNoHeader1=new MemoryStream();
    MemoryStream wavNoHeader2 = new MemoryStream();
    //result WAV stream
    MemoryStream wav=new MemoryStream();
    //create & write header
    ushort numchannels = 1;
    ushort samplelength = 1; // in bytes
    uint samplerate = 22050;
    int wavsize = (int) ((wavNoHeader1.Length + wavNoHeader2.Length)/(numchannels*samplelength));
    BinaryWriter wr = new BinaryWriter(wav);
    wr.Write(Encoding.ASCII.GetBytes("RIFF"));
    wr.Write(36 + wavsize);
    wr.Write(Encoding.ASCII.GetBytes("WAVEfmt "));
    wr.Write(16);
    wr.Write((ushort)1);
    wr.Write(numchannels);
    wr.Write(samplerate);
    wr.Write(samplerate * samplelength * numchannels);
    wr.Write(samplelength * numchannels);
    wr.Write((ushort)(8 * samplelength));
    wr.Write(Encoding.ASCII.GetBytes("data"));
    wr.Write(numsamples * samplelength);
    //append data from raw streams
    wavNoHeader1.CopyTo(wav);
    wavNoHeader2.CopyTo(wav);
    //play
    wav.Position = 0;
    SoundPlayer sp=new SoundPlayer(wav);
    sp.Play();