播放音乐javascript

编程入门 行业动态 更新时间:2024-10-24 14:25:21
本文介绍了播放音乐javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的代码如下.基本上,我的目标是一旦用户单击某个按钮,我将获得此按钮的ID并通过ajax发送,然后根据指定的ID返回mp3网址并播放声音.一切正常,但问题是我不知道如何停止或暂停音乐.我试过audio.stop()或audio.pause().没有人在工作.

My code is below. Basically, my goal is once the user clicks certain button, I would get this button's id and send it through ajax, then return the mp3 url based on the id specified and play the sound. Everything is working perfectly fine, but the problem is I do not know how to stop or pause the music. I've tried audio.stop(), or audio.pause(). Neither one is working.

一旦用户单击某个按钮,我想停止所有音乐并播放被单击的新音乐.

Once the user clicks certain button, i would like to stop all the music and play the new one that is clicked.

$('.play_sound').click(function(event){ event.preventDefault(); var data_id = $(this).parents('tr').attr('data-id'); $.post('ajax/play_sound.php', {data_id: data_id}, function(data){ var audio = new Audio(data); audio.play(); }); });

推荐答案

由于您创建了audio作为匿名函数范围内的局部变量,因此无法暂停它.

Because you created audio as a local variable in the scope of the anonymous function, you can't pause it.

最简单的解决方案是将audio设置为全局.

The simplest solution is to make audio global.

如果您计划支持多个音频对象,则更好的方法是创建一个像AudioPool这样的对象,并且还可以添加结束"之类的事件.

if you plan to support more than one audio object, a better approach is to create an Object like an AudioPool and you could also add Events like "ended".

var audio; $('.pause_sound').click(function(event){ event.preventDefault(); if (!audio.paused) { audio.pause(); } }); $('.stop_sound').click(function(event){ event.preventDefault(); audio.stop(); }); $('.play_sound').click(function(event){ event.preventDefault(); var data_id = $(this).parents('tr').attr('data-id'); $.post('ajax/play_sound.php', {data_id: data_id}, function(data){ // audio of global scope audio = new Audio(data); audio.play(); }); });

carlodurso建议使用另一种解决方案来查询DOM并为audio创建HTML元素.

An alternative solution is suggested by carlodurso to query the DOM and create an HTML element for audio.

更多推荐

播放音乐javascript

本文发布于:2023-07-11 09:10:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1093535.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:音乐   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!