好吧,我能够得到它。不确定它是否是最好的方法,但它似乎运作良好。
我必须添加 blazor 存储扩展:
https://github.com/BlazorExtensions/Storage
它充当 .NET 的 JavaScript SessionStorage 和 LocalStorage 的代理。加载后,我从 .NET 添加了每个嵌入式 wav 文件,如下所示:
foreach (var kvp in SoundStreamDictionary)
{
await sessionStorage.SetItem(
kvp.Key.ToString().ToLower() //Key is the name of the sound
, kvp.Value.ToBase64() //Value is a Stream object
);
}
这ToBase64
是非常标准的 .NET 流操作:
public static string ToBase64(this Stream stream)
{
byte[] bytes;
using (var memoryStream = new MemoryStream())
{
stream.Position = 0;
stream.CopyTo(memoryStream);
bytes = memoryStream.ToArray();
}
return Convert.ToBase64String(bytes);
}
现在所有数据都作为字符串存储在 JavaScript SessionStorage 中。诀窍现在是将其解码为音频。在这个 JS 辅助方法的帮助下(感谢这个StackOverflow 帖子):
function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
return new Blob(byteArrays, { type: contentType });
}
把它和这个放在 BlazorComponent 的 JsInterop.js 文件中:
const soundAudios = [];
window.JsSound = {
loadSounds: function (sounds) {
sounds.forEach(sound => {
//Blazor.Storage extension adds extra double quotes so trim
const str64 = sessionStorage.getItem(sound.path).slice(1, -1);
const blob = b64toBlob(str64, "audio/wav");
const blobUrl = URL.createObjectURL(blob);
const audio = new Audio(blobUrl);
soundAudios[sound.id] = audio;
});
return true;
},
play: function (id) {
const audio = soundAudios[id];
audio.currentTime = 0;
audio.play();
return true;
},
};
最后声音可以从.Net中通过名称调用:
private IDictionary<string, int> soundDict = new Dictionary<string, int>();
public Task<string> LoadSounds(IEnumerable<string> fileNames)
{
var sounds = fileNames
.Select(name =>
{
var snd = new
{
id = soundDict.Count,
path = name
};
soundDict.Add(name, snd.id);
return snd;
})
.ToList();
return JSRuntime.Current.InvokeAsync<string>(
"JsSound.loadSounds"
, sounds
);
}
public Task<string> Play(string name)
{
return JSRuntime.Current.InvokeAsync<string>(
"JsSound.play"
, soundDict[name]
);
}