How to play extracted wave file byte array in C#?

2019-07-03 23:25发布

问题:

At the moment i have managed to separate the left and right channel of a WAVE file and have included the header in a byte[] array. My next step is to be about to play both channels. How can this be done?

Here is a code snippet:

byte[] song_left = new byte[fa.Length];
byte[] song_right = new byte[fa.Length];

int p = 0;

for (int c = 0; c < 43; c++)
{
    song_left[p] = header[c];
    p++;
}

int q = 0;

for (s = startByte; s < length; s = s + 3)
{
    song_left[s] = sLeft[q];
    q++;
    s++;
    song_left[s] = sLeft[q];
    q++;
}

p = 0;

for (int c = 0; c < 43; c++)
{
    song_right[p] = header[c];
    p++;
}

This part is reading the header and data from both the right and light channel and saving it to array sLeft[] and sRight[]. This part is working perfectly.

Once I obtained the byte arrays, I did the following:

System.IO.File.WriteAllBytes("c:\\left.wav", song_left);

System.IO.File.WriteAllBytes("c:\\right.wav", song_right);

Added a button to play the saved wave file:

private void button2_Click(object sender, EventArgs e)
{
    spWave = new SoundPlayer("c:\\left.wav");
    spWave.Play();          
}

Once I hit the play button, this error appers:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.dll

Additional information: The wave header is corrupt.

Any ideas?

回答1:

For "separate the left and right channel of a WAVE file" use AudioCompressionManager.SplitStereo method from http://alvas.net/alvas.audio.aspx

Code below for your purpose

        IntPtr formatMono = AudioCompressionManager.CreateFormat(formatArray);
        IntPtr formatStereo = IntPtr.Zero;
        byte[] dataStereo = null;
        AudioCompressionManager.MergeStereo(formatMono, leftData, rightData, ref formatStereo, ref dataStereo);
        PlayerEx plex = new PlayerEx();
        plex.OpenPlayer(formatStereo);
        plex.AddData(dataStereo);
        plex.StartPlay();


回答2:

I have a library up on codeplex for playing wave-form data.

http://WinMM.codeplex.com

I have a project that does a lot with sound loading and playing based on the above library:

http://files.otac0n.com/ShadySound.zip
(This link may take a while to start working, i just created that subdomain.)

It has a few projects in it, because everything is loaded through a plug-in infrastructure, but it does show how to load a WAV file.

Unfortunately, the question you have is a little bit too "big" for a QA site like this, but I'd be happy to talk with you offline about this.



标签: c# audio wav