Convert byte array to wav file

青春壹個敷衍的年華 提交于 2021-01-20 16:37:07

问题


I'm trying to play a wav sound that stored in byte array called bytes. I know that I should convert the byte array to wav file and save it in my local drive then called the saved file but I was not able to convert the byte array to wav file.

please help me to give sample code to convert byte arrary of wav sound to wav file.

here is my code:

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();
}

回答1:


Try this:

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



回答2:


You can use something like File.WriteAllBytes(path, data) or...

...Alternatively if you don't want to write the file you could convert the byte array to a stream and then play that...

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 :-)




回答3:


Using NAudio and you can try something like:

//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*/);
    //}
}


来源:https://stackoverflow.com/questions/2665362/convert-byte-array-to-wav-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!