I would look at similar topics.But I don't understand. There are more than one project in mvc solution. I would like to play an audio file using javascript in cshtml in the "voucher" project.This file is in the "content" folder under the "main" project. I can relate to the projects at the controller level.But I had a problem with the view level.

<script>
var audio = new Audio();
audio.src = ""; // I could not add the path of the file.
audio.play();
</script>

I've tried this way:

audio.src = "@Server.MapPath("~/Content/sounds/beep.wav")";

I've also tried using html5. But again I could not access the other project in the "src". I tried converting the audio file into a byte on the controller part. But I didn't have a useful result.

2 Answers

2
Faraz On Best Solutions

You can serv like this:

    [HttpGet]
        public ActionResult GetAudioFile(string filename)
        {
string filePath = Server.MapPath(Url.Content($"~/Content/sounds/{filename}"));
            var bytes = new byte[0];


            using (var fs = new FileStream(filePath , FileMode.Open, FileAccess.Read)
            {
                var br = new BinaryReader(fs);
                long numBytes = new FileInfo(fileLocation).Length;
                buff = br.ReadBytes((int)numBytes);
            }

            return File(buff, "audio/mpeg", "file.mp3");
        }

And then in your java script code:

function Sound(source, volume, loop)
{
    this.source = source;
    this.volume = volume;
    this.loop = loop;
    var son;
    this.son = son;
    this.finish = false;
    this.stop = function()
    {
        document.body.removeChild(this.son);
    }
    this.start = function()
    {
        if (this.finish) return false;
        this.son = document.createElement("embed");
        this.son.setAttribute("src", this.source);
        this.son.setAttribute("hidden", "true");
        this.son.setAttribute("volume", this.volume);
        this.son.setAttribute("autostart", "true");
        this.son.setAttribute("loop", this.loop);
        document.body.appendChild(this.son);
    }
    this.remove=function()
    {
        document.body.removeChild(this.son);
        this.finish = true;
    }
    this.init = function(volume, loop)
    {
        this.finish = false;
        this.volume = volume;
        this.loop = loop;
    }
}

Also used like this way:

var url= 'ControllerName/GetAudioFile?filename=yourfilename '
var foo = new Sound("url", 100, true);
foo.start();
foo.stop();
foo.start();
foo.init(100, false);
0
uyusuk On

i tried the following code:

<script>
    $(document).ready(function () {
var url = "@Url.Content("~/Content/sounds/notificationSound.mp3")";
    new Audio(url).play();
}</script>

The code worked when I refresh the page. Then I pressed ctrl + f5. But this time not worked. The error message is displayed on the screen. Error message :

Uncaught (in promise) DOMException