I am building a small morse code app. I have the "Dash.mp3" and "Dot.mp3" on my computer and I am parsing it into bytes. I then take the bytes and "build" the sound based on the input. example:
"SOS" = ... --- ... . = "dot.mp3" = bytes = [10,20] (example).
- = "dash.mp3" = bytes = [30,40] (example). so the end output in bytes would be :
[10,20,10,20,10,20,30,40,30,40,30,40,10,20,10,20,10,20]
I then send these bytes as A stream in response to the AJAX call.
it seems like when the input is short like "SOS" it works, but when it gets longer like "SOSSS" it freezes. no idea why. hope someone could help me/ suggest maybe a different approach to building the sounds.
AJAX:
$(function () {
var q = $.QueryString["msg"];
$.ajax({
type: "POST",
url: "/morse",
dataType: 'JSON',
data: q,
success: function (data) {
console.log("yay");
},
error: function (req, status, error) {
console.log("nay");
}
});
});
Controller action:
[Route("morse")]
public async Task<ActionResult<byte[]>> Morse(string msg)
{
var sound = await Task.FromResult(_decoder.MorseBuilder(msg));
MemoryStream stream = new MemoryStream(sound);
return File(stream, "audio/mp3");
}
The morse builder class:
public class MorseDecoder : IMorseDecoder
{
readonly byte[] dot;
readonly byte[] dash;
public MorseDecoder()
{
dot = System.IO.File.ReadAllBytes("C:\\Users\\Feuse135\\source\\repos\\MorseCodeServer\\wwwroot\\audio\\dot.mp3");
dash = System.IO.File.ReadAllBytes("C:\\Users\\Feuse135\\source\\repos\\MorseCodeServer\\wwwroot\\audio\\dash.mp3");
}
public byte[] MorseBuilder(string msg)
{
var decoded = Decode(msg); // turns string into morse (..-.-.-)
List<byte> sound = new List<byte>();
foreach (var letter in decoded)
{
switch (letter)
{
case '.':
foreach (var item in dot)
{
sound.Add(item);
}
break;
case '-':
foreach (var item in dash)
{
sound.Add(item);
}
break;
default:
break;
}
}
return sound.ToArray();
}
}
EDIT UPDATE:
I made it so I download the file after finishing the bytes build and seeing if its corrupts, the .mp3 file works perfectly even with "SSSSSSSSSSSSSSSSSSSSS" it seems that the problem starts when I return the file back to the view...maybe there is some MAX capacity on response?
[Route("morse")] public ActionResult Morse(string msg) {
var sound = _decoder.MorseBuilder(msg);
System.IO.File.WriteAllBytes("C:\\Users\\Feuse135\\source\\repos\\MorseCodeServer\\wwwroot\\audio\\somefile.mp3", sound);
var f = System.IO.File.ReadAllBytes("C:\\Users\\Feuse135\\source\\repos\\MorseCodeServer\\wwwroot\\audio\\somefile.mp3");
return File(f, "audio/mpeg");
}