使用jQuery / Javascript播放歌曲

时间:2017-11-11 22:24:04

标签: javascript jquery html events audio

当文件从Arduino收到'playMusic'事件时,我正在尝试播放一首歌,但我得到的是Uncaught TypeError: Cannot read property 'play' of undefined at EventSource.<anonymous>。我已经读到这可能是因为音频在歌曲文件准备好之前正在尝试播放,但在事件监听器中组合window.onload函数不会导致任何事情发生。我在调用事件之前添加了两秒的延迟,试图补偿足够的时间加载歌曲文件,但我仍然得到同样的错误。

<html>
    <title>Song Time</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>

    <body>
        <audio id="song">
            <source src="song.mp3" type="audio/mpeg">
        </audio>

         <script type="text/javascript">
           var eventSource = new EventSource("https://api.particle.io/v1/devices/2d0024001047363330363431/events/?access_token=bdde583943e53ea709aa421a2e618d024700b2f1");

           eventSource.addEventListener('playMusic', function(e) {
                //window.onload=function() {
                    console.log("here");
                    $('song')[0].play();
                //}

           });
        </script>
    </body>
</html>
Uncaught TypeError: Cannot read property 'play' of undefined
    at EventSource.<anonymous

2 个答案:

答案 0 :(得分:0)

这似乎是这个函数的jQuery问题,函数document.getElementById("play").addEventListener('click', function(e) { console.log("play"); document.getElementById("song").play(); }); document.getElementById("stop").addEventListener('click', function(e) { console.log("stop"); document.getElementById("song").pause(); document.getElementById("song").currentTime = 0; }); document.getElementById("pause").addEventListener('click', function(e) { console.log("stop"); document.getElementById("song").pause(); });与纯js一起工作正常。 这里是片段:

&#13;
&#13;
<html>
<title>Song Time</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>

<body>
  <audio id="song">
            <source src="http://www.cedarhome.org/mp3/songs/01%20Battlecry.mp3" type="audio/mpeg">
  </audio>
  <br />
  <input type="button" value="play" id="play" /><br />
  <input type="button" value="pause" id="pause" /><br />
  <input type="button" value="stop" id="stop" /><br />
</body>

</html>
&#13;
necessary_sequence = [20, 56, 2]

first_num = necessary_sequence[0]
second_num = necessary_sequence[1]
third_num = necessary_sequence[2]
test_list = [43, 12, 20, 20, 56, 56, 2, 4, 98, 20] #should print output_2, but printing output_1 (order rule is not observed)  

if first_num in test_list and second_num in test_list and third_num in test_list:
    if test_list.index(first_num) < test_list.index(second_num) < test_list.index(third_num):
        print("output_1: all three numbers are in the list in order")
    else:
        print("output_2: the numbers are either missing from the list or are not in order")
&#13;
&#13;
&#13;

答案 1 :(得分:0)

归功于@James

$('#shop')你忘了# - 詹姆斯