我的代码如下.基本上,我的目标是一旦用户单击某个按钮,我将获得此按钮的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
发布评论