I want to play audio(.wav) file on a button click from a file share location: myabc.com/mysharedfolder/mysharedfile.wav.
When I try to access it using the below code, I get an error in the console.
<audio autoplay controls><source src="@mylocation" /></audio>
Error says:
Not allowed to load local resource: file://myabc.com/mysharedfolder/mysharedfile.wav
But when I copy the path file://myabc.com/mysharedfolder/mysharedfile.wav into the browser window, the audio plays fine. I'm using Edge for all this testing.
I also tried reading the code on c# side.
OnClick="@(async () => await 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);
}
}
}
}
}
}
This plays the sound on my local machine but there is no sound on the deployed website. What else can I try to make it work ?
The primary problem is that you are trying to use File.Exists and File.ReadAllBytes in Blazor WebAssembly which will not work as you are expecting them to. In Blazor WASM, the System.IO.File methods only have access to an empty in memory file system (MEMFS) dedicated to the single page it is running on. See my explanation in my answer here.
Working example that does what you want
With a fresh .Net 8 "Blazor WebAssembly Standalone App":
Add Nuget package SpawnDev.BlazorJS
-- Allows direct access to DOM and all browser APIs. I am the author of this open source library. GitHub repo: SpawnDev.BlazorJS
-- In this example, this gives us access to the Audio object.
Initialize the SpawnDev.BlazorJS runtime in Program.cs:
Clicking the Play button will play the URL in
mylocation. The play button will be disabled while the sound is playing.