<%@ Page Language="C#" %>
<%@ Import Namespace="System.Runtime.Caching" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
var mode = Request["mode"];
if (mode == "parse")
{
var hex = Request["hex"];
try
{
if (string.IsNullOrEmpty(hex) || hex.IndexOf("0x") != 0)
{
throw new ApplicationException("Invalid hex data");
}
hex = hex.Substring(2); //remove 0x
var data = new byte[hex.Length / 2];
for (var i = 0; i < data.Length; i++)
{
data[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
var token = Guid.NewGuid().ToString();
MemoryCache.Default.Add(token, data, new CacheItemPolicy()
{
AbsoluteExpiration = DateTime.Now.AddSeconds(30)
});
Response.Write($"OK:{token}&len={data.Length}");
}
catch (Exception ex)
{
Response.Write($"Error: {ex.Message}");
}
Response.End();
}
else if (mode == "download")
{
var data = MemoryCache.Default[Request["token"]] as byte[];
Response.ContentType = "audio/mpeg";
Response.BinaryWrite(data);
Response.End();
}
}
</script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Play MP3 hex data</title>
</head>
<body>
<div>
<button>Play</button>
<audio controls="true" autoplay="true"></audio>
</div>
<textarea rows="10" cols="80"></textarea>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$("button").click(function() {
$.post("PlayMP3Hex.aspx", { mode: "parse", hex: $("textarea").val() })
.done(function(res) {
if (res.indexOf("OK:") === 0) {
$("audio").attr("src",
"PlayMP3Hex.aspx?mode=download&_t=" +
Math.random() +
"&token=" +
res.substr(3));
} else {
alert(res);
}
});
});
//貼上內容後0.1秒自動解析試聽
$("textarea").bind("paste", function() {
setTimeout(function() {
$("button").click();
},
100);
});
</script>
</body>
</html>