I've been following tutorials like these (1, 2) to try to build a .wav file. However, I can't seem to get it to work because the wav file will open properly but be listed as 0 seconds and not play anything.
Code (it's bad because it's merely a test to try and get it to work):
using System;
using System.IO;
using System.Linq;
using System.Text;
namespace Namespace
{
class Program
{
static void Main()
{
StringBuilder SB = new StringBuilder();
for (int e = 0; e < 200000; e++)
{
SB.Append(" ff");
}
int Size = SB.Length / 3;
StringBuilder SBHexSize = new StringBuilder(Convert.ToString(Size, 16));
while (SBHexSize.Length < 8)
{
SBHexSize.Append("0");
}
string HexSize = SBHexSize.ToString();
const string RIFF = "52 49 46 46";
const string RestOfHeader = "57 41 56 45 66 6d 74 20 10 00 00 00 01 00 02 00 22 56 00 00 88 58 01 00 04 00 10 00 64 61 74 61 00 08 00 00";
//Console.WriteLine($"{RIFF} {HexSize[6..8]} {HexSize[4..6]} {HexSize[2..4]} {HexSize[..2]} {RestOfHeader}{SB.ToString()}");
//System.Threading.Thread.Sleep(-1);
//ByteArray bytes = new ByteArray($"{RIFF} {HexSize[6..8]} {HexSize[4..6]} {HexSize[2..4]} {HexSize[..2]} {RestOfHeader}{SB.ToString()}");
ByteArray bytes = new ByteArray($"{RIFF} FF FF FF FF {RestOfHeader}{SB.ToString()}");
bytes.Write();
}
}
class ByteArray
{
private byte[] array;
public ByteArray(string hex)
{
array = Enumerable.Range(0, hex.Length)
.Where(x => x % 3 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
public void Write()
{
File.WriteAllBytes(@"C:\Users\name\source\repos\MusicCreator\MusicCreator\musictest.wav", array);
}
}
}
Is it a problem with the code, like how I'm trying to write the bytes, or is it something with the bytes themselves?
The header of the
WAVfile must include the length of the data:You have the length hard-coded:
64 61 74 61("data")00 08 00 00(length)But you should be writing the length of the data here, e.g.
30 D4 00 00This is why in the sample that you linked, there is a "finalize" section where they write the length of the data back into the header.