Search code examples
.netasp.net-mvcaudiohtml5-audioaudio-recording

HTML5 audio recorder stream and upload to MVC server - Why is it noisy?


I'm trying to make a web audio recorder using getUserMedia and .NET MVC.

I got as far as recording it and sending the chunks of data to the server. The problem is that i can't play the results. The code below is the closer I got from playing it correctly, I can record and hear my voice in the recording but I'm getting a lot of white noise in it. I'm probably messing around with the enconding or parsing of the data. Here are some of the code:

chan = e.inputBuffer.getChannelData(channel);
buffer.push(chan);
var conv_buffer = convertFloat32ToInt16(chan);
uploadAudio(conv_buffer);

    function convertFloat32ToInt16(buffer) {
    l = buffer.length;
    buf = new Int16Array(l);
    while (l--) {
        buf[l] = Math.min(1, buffer[l]) * 0x7FFF;
    }
    return buf;
}

At the server side I'm storing the chunks with their order into a Session (don't know if I should use anything else here. Session doesn't sound right for me):

 if (Session["wave"] == null)
            Session["wave"] = new Dictionary<string, string>();
 if (Request.Files.Count == 0)
            ((Dictionary<string, string>)Session["wave"]).Add(Request.Form[0], Request.Form[1]);

After the end of the recording I'm just parsing the string I streamed to a float array, encoding with NAudio and saving to disk:

 List<float> list = new List<float>();
            foreach (var item in ((Dictionary<string, string>)Session["wave"]).OrderBy(c => c.Key))
            {
                list.AddRange(StringToFloatArray(item.Value).ToList());
            }
            Random rand = new Random();

            WaveFormat waveFormat = new WaveFormat(48000, 16, 1);
            string fileName = "teste" + rand.Next(0, 999999).ToString() + ".wav";

            WaveFileWriter writer = new WaveFileWriter("c:\\" + fileName, waveFormat);

            writer.WriteSamples(list.ToArray(), 0, list.Count());

            writer.Close();

The parsing:

        private float[] StringToFloatArray(string input)
    {
        var strs = input.Split(',');
        float[] arr = new float[strs.Length];
        for (int i = 0; i < (strs.Length - 1)/2; i++)
        {
            arr[i] = float.Parse(strs[i]);
        }
        return arr;
    }

It would make me very happy if anyone could help me or point in any direction. I already tried changing the enconding in a lot of ways without success...


Solution

  • Many time latter i realize what i needed to do. The problem was that i need to convert back from int16 to float to pass it to NAudio.

    buffer[k] = float.Parse(strs[k].Replace(".", ",")) / 32767.5f;