WaveHeaderWriter.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.Net;
  3. using System.Windows;
  4. using System.Windows.Controls;
  5. using System.Windows.Documents;
  6. using System.Windows.Ink;
  7. using System.Windows.Input;
  8. using System.Windows.Media;
  9. using System.Windows.Media.Animation;
  10. using System.Windows.Shapes;
  11. namespace VocabManager.Voice
  12. {
  13. public class WaveHeaderWriter
  14. {
  15. static byte[] RIFF_HEADER = new byte[] { 0x52, 0x49, 0x46, 0x46 };
  16. static byte[] FORMAT_WAVE = new byte[] { 0x57, 0x41, 0x56, 0x45 };
  17. static byte[] FORMAT_TAG = new byte[] { 0x66, 0x6d, 0x74, 0x20 };
  18. static byte[] AUDIO_FORMAT = new byte[] { 0x01, 0x00 };
  19. static byte[] SUBCHUNK_ID = new byte[] { 0x64, 0x61, 0x74, 0x61 };
  20. private const int BYTES_PER_SAMPLE = 2;
  21. public static void WriteHeader(
  22. System.IO.Stream targetStream,
  23. int byteStreamSize,
  24. int channelCount,
  25. int sampleRate)
  26. {
  27. int byteRate = sampleRate * channelCount * BYTES_PER_SAMPLE;
  28. int blockAlign = channelCount * BYTES_PER_SAMPLE;
  29. targetStream.Write(RIFF_HEADER, 0, RIFF_HEADER.Length);
  30. targetStream.Write(PackageInt(byteStreamSize + 36, 4), 0, 4);
  31. targetStream.Write(FORMAT_WAVE, 0, FORMAT_WAVE.Length);
  32. targetStream.Write(FORMAT_TAG, 0, FORMAT_TAG.Length);
  33. targetStream.Write(PackageInt(16, 4), 0, 4);//Subchunk1Size
  34. targetStream.Write(AUDIO_FORMAT, 0, AUDIO_FORMAT.Length);//AudioFormat
  35. targetStream.Write(PackageInt(channelCount, 2), 0, 2);
  36. targetStream.Write(PackageInt(sampleRate, 4), 0, 4);
  37. targetStream.Write(PackageInt(byteRate, 4), 0, 4);
  38. targetStream.Write(PackageInt(blockAlign, 2), 0, 2);
  39. targetStream.Write(PackageInt(BYTES_PER_SAMPLE * 8), 0, 2);
  40. //targetStream.Write(PackageInt(0,2), 0, 2);//Extra param size
  41. targetStream.Write(SUBCHUNK_ID, 0, SUBCHUNK_ID.Length);
  42. targetStream.Write(PackageInt(byteStreamSize, 4), 0, 4);
  43. }
  44. static byte[] PackageInt(int source, int length = 2)
  45. {
  46. if ((length != 2) && (length != 4))
  47. throw new ArgumentException("length must be either 2 or 4", "length");
  48. var retVal = new byte[length];
  49. retVal[0] = (byte)(source & 0xFF);
  50. retVal[1] = (byte)((source >> 8) & 0xFF);
  51. if (length == 4)
  52. {
  53. retVal[2] = (byte)((source >> 0x10) & 0xFF);
  54. retVal[3] = (byte)((source >> 0x18) & 0xFF);
  55. }
  56. return retVal;
  57. }
  58. }
  59. }