播放音乐javascript [英] play music javascript

查看:107
本文介绍了播放音乐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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆