我想通过从文件共享位置单击按钮来播放音频(.wav)文件:myabc.com/mysharedfolder/mysharedfile.wav.
当我尝试使用以下代码访问它时,控制台中出现错误。
<audio autoplay controls><source src="@mylocation" /></audio>
错误说:
不允许加载本地资源: 文件://myabc.com/mysharedfolder/mysharedfile.wav
但是当我将路径 file://myabc.com/mysharedfolder/mysharedfile.wav 复制到浏览器窗口中时,音频播放正常。我使用 Edge 进行所有这些测试。
我也尝试阅读c#端的代码。
OnClick =“@(async()=>等待PlaySound())”
using NAudio.Wave;
private async Task PlaySound()
{
string mylocation = myabc.com/mysharedfolder/mysharedfile.wav";
if (File.Exists(mylocation))
{
byte[] bytes = System.IO.File.ReadAllBytes(mylocation);
using (var stream = new MemoryStream(bytes))
{
using (var reader = new WaveFileReader(stream))
{
using (var waveOut = new WaveOutEvent())
{
waveOut.Init(reader);
waveOut.Play();
while (waveOut.PlaybackState == PlaybackState.Playing)
{
System.Threading.Thread.Sleep(200);
}
}
}
}
}
}
这会在我的本地计算机上播放声音,但部署的网站上没有声音。我还能尝试什么才能让它发挥作用?
主要问题是您尝试在 Blazor WebAssembly 中使用 File.Exists 和 File.ReadAllBytes,但它们无法按您的预期工作。 System.IO.File 方法只能访问专用于其正在运行的单个页面的内存中的空文件系统。请参阅我的回答中的解释这里。
使用新的 .Net 8“Blazor WebAssembly 独立应用程序”:
添加Nuget包SpawnDev.BlazorJS
-- 允许直接访问 DOM 和所有浏览器 API。我是这个开源库的作者。 GitHub 存储库:SpawnDev.BlazorJS
-- 在此示例中,这使我们能够访问 Audio 对象。
在Program.cs中初始化SpawnDev.BlazorJS运行时:
// add using
using SpawnDev.BlazorJS;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
// add below line to init SpawnDev.BlazorJS runtime
builder.Services.AddBlazorJSRuntime();
// rest of Program.cs
@page "/counter"
@using SpawnDev.BlazorJS.JSObjects
<PageTitle>Play WAV</PageTitle>
<h1>Play WAV</h1>
<button disabled="@IsPlaying" class="btn btn-primary" @onclick="PlaySound">Click me</button>
@code {
bool IsPlaying = false;
private async Task PlaySound()
{
IsPlaying = true;
string mylocation = "https://www2.cs.uic.edu/~i101/SoundFiles/CantinaBand3.wav";
using var audio = new Audio(mylocation);
var tcs = new TaskCompletionSource();
var onError = new Action(() => tcs.SetException(new Exception("Play failed")));
var OnEnded = new Action(() => tcs.SetResult());
audio.OnError += onError;
audio.OnEnded += OnEnded;
try
{
await audio.Play();
await tcs.Task;
}
finally
{
audio.OnError -= onError;
audio.OnEnded -= OnEnded;
IsPlaying = false;
}
}
}