繁体   English   中英

如何使用JavaScript在MVC项目中播放mp3文件?

[英]How to play mp3 file in a mvc project using javascript?

我会看类似的话题,但是我听不懂。 mvc解决方案中有多个项目。 我想在“凭证”项目中的cshtml中使用javascript播放音频文件。此文件位于“主”项目下的“内容”文件夹中。 我可以在控制器级别关联项目,但是我在视图级别存在问题。

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

我已经尝试过这种方式:

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

我也尝试使用html5。 但是同样,我无法访问“ src”中的另一个项目。 我尝试将音频文件转换为控制器部分的字节。 但是我没有得到有用的结果。

您可以这样服务:

    [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");
        }

然后在您的Java脚本代码中:

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;
    }
}

也像这样使用:

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

我尝试了以下代码:

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

刷新页面后,代码有效。 然后按Ctrl + F5。 但是这次没有用。 错误消息显示在屏幕上。 错误信息 :

未捕获(承诺)的DOMException

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM