superuser
superuser

Reputation: 33

Wave Header corrupted

I want to do some changing on Wave file, then Play it Directly after doing that.

So I define a byte array to store the bytes of wave file on it as following:

byte[] byteArr;
byteArr = File.ReadAllBytes(dlg.FileName);

where dlg is an OpenFile Dialog.

Then I do a changing to sample bit rate of wave as following:

private void playSlectedWave_Click(object sender, EventArgs e)
{
    int sample = 50000;
    MemoryStream fs = new MemoryStream(byteArr);
    BinaryReader br = new BinaryReader(fs);
    int length = (int)fs.Length-8;
    fs.Position = 22;
    short channels = br.ReadInt16();
    fs.Position = 34;
    short BitsPerSample = br.ReadInt16();
    byte[] arrfile = new byte[fs.Length];
    fs.Position = 0;
    fs.Read(arrfile, 0, arrfile.Length);
    BinaryWriter bw = new BinaryWriter(fs);
    bw.BaseStream.Seek(0, SeekOrigin.Begin);
    bw.Write(arrfile, 0, 24); 
    bw.Write(sample);
    bw.Write((int)(sample* ((BitsPerSample * channels) / 8)));
    bw.Write((short)((BitsPerSample * channels) / 8));
    bw.Write(arrfile, 34, arrfile.Length - 34);
    SoundPlayer SP = new SoundPlayer(fs);
    SP.Play();
}

My question is that when it reaches the SP.Play() it throws an exception that says that the Wave Header is corrupted.

For more Information, I try the previous code but with FileStream instead of MemoryStream and it works fine for me .

Does Anyone know why?

Upvotes: 1

Views: 4031

Answers (3)

user3344460
user3344460

Reputation:

Format your desired audio file correctly to a .wav file!

I thought this would work:

soundPlayer.Stream.Position = 0;

But sadly, it compiled to no avail...

Try this site to format: http://audio.online-convert.com/convert-to-wav

Upvotes: 0

Mr Dog
Mr Dog

Reputation: 396

Define your SoundPlayer SP outside of your sub/function or use

SP.PlaySync

SP.Play();

Is Async, after hitting that line you leave the Sub while it is still playing in the background and the memorystream is likely modified or removed from memory.

You are lucky that you only get an exception, there is a possibility that your program would just crash even when debugging without any exception.

Upvotes: 2

M.Eren Çelik
M.Eren Çelik

Reputation: 155

Try:

SP.Stream.Position = 0;

It was a solution at least for my situation.

Upvotes: 2

Related Questions