将字节数组转换为wav文件

时间:2010-04-19 05:41:28

标签: c# bytearray wav

我正在尝试播放存储在名为bytes的字节数组中的wav声音。 我知道我应该将字节数组转换为wav文件并将其保存在我的本地驱动器中,然后调用保存的文件,但我无法将字节数组转换为wav文件。

请帮我提供示例代码,将wav声音的字节转换为wav文件。

这是我的代码:

protected void Button1_Click(object sender, EventArgs e)
{
    byte[] bytes = GetbyteArray();

   //missing code to convert the byte array to wav file

    .....................

    System.Media.SoundPlayer myPlayer = new System.Media.SoundPlayer(myfile);
    myPlayer.Stream = new MemoryStream();
    myPlayer.Play();
}

3 个答案:

答案 0 :(得分:9)

试试这个:

System.IO.File.WriteAllBytes("yourfilepath.wav", bytes);

答案 1 :(得分:7)

您可以使用File.WriteAllBytes(path, data)或......

之类的内容

...或者如果您不想编写文件,可以将字节数组转换为流然后播放...

var bytes = File.ReadAllBytes(@"C:\WINDOWS\Media\ding.wav"); // as sample

using (Stream s = new MemoryStream(bytes))
{
    // http://msdn.microsoft.com/en-us/library/ms143770%28v=VS.100%29.aspx
    System.Media.SoundPlayer myPlayer = new System.Media.SoundPlayer(s);
    myPlayer.Play();
}

PK: - )

答案 2 :(得分:1)

使用NAudio,您可以尝试以下内容:

//var wavReader = new WaveFileReader(yourWavFilePath);
//byte[] buffer = new byte[2 * wav1Reader.WaveFormat.SampleRate * wav1Reader.WaveFormat.Channels];
byte[] buffer = YourWaveSoundByteArray;

using ( WaveFileWriter writer = new WaveFileWriter(YourOutputFilePath, new WaveFormat( AssignWaveFormatYouWant /*wavReader.WaveFormat.SampleRate, 16, 2/*how many channel*/))
    )
{
    //int bytesRead;
    //while ((bytesRead = wavReader.Read(buffer, 0, buffer.Length)) > 0)
    //{
        writer.Write(buffer, 0,  buffer.Length/*bytesRead*/);
    //}
}
相关问题