【问题标题】:How to reproduce a sound sequence using <audio> tag html5 [closed]如何使用 <audio> 标签 html5 重现声音序列 [关闭]
【发布时间】:2015-12-29 15:44:24
【问题描述】:

其实我是 Ruby on Rails 4 中使用 HTML5 编程的新手,所以问题来了:

如何在 Rails 4 应用程序上重现定义的声音序列? 我的意思是,我需要听不同的声音一一再现,并且每个声音之间应该有一个时间间隔。

例子:

START  
< sound 1 >
1 sec of silence 
< sound 2 >  
1 sec of silence 
< sound n >  
END

我还需要声音序列必须自己统计/自动播放。 帮助!! :D

【问题讨论】:

    标签: javascript ruby html ruby-on-rails-4 audio


    【解决方案1】:

    一个 javascript 函数,它获取 audio 元素列表并在它们之间以 1 秒的暂停时间播放它们。

    包含在 html 文档的末尾。

    (function() {
      var track1 = document.getElementById('track1');
      var track2 = document.getElementById('track2');
      var track3 = document.getElementById('track3');
    
      var trackList = [];
    
      trackList.push(track1);
      trackList.push(track2);
      trackList.push(track3);
    
      playTracks(trackList); // call the function so it starts playing the 1st song
    
      ///
      // plays a list of audio elements
      function playTracks(tracks) {
        var curentSong = tracks.shift(); // take out the 1st song in order to play it
        curentSong.play(); // play it
        curentSong.onended = function() { // when it ends
          setTimeout(function() { // wait 1 second
            playTracks(tracks); // play the rest of the list
          }, 1000);
        };
      }
    })(); // IIFE so it starts as soon as it's loaded
    

    启动它的另一个选项是在 window.onload 事件上。

    function startMusic() {
      var track1 = document.getElementById('track1');
      var track2 = document.getElementById('track2');
      var track3 = document.getElementById('track3');
    
      var trackList = [];
    
      trackList.push(track1);
      trackList.push(track2);
      trackList.push(track3);
    
      playTracks(trackList); // call the function so it starts playing the 1st song
    
      ///
      // plays a list of audio elements
      function playTracks(tracks) {
        var curentSong = tracks.shift(); // take out the 1st song in order to play it
        curentSong.play(); // play it
        curentSong.onended = function() { // when it ends
          setTimeout(function() { // wait 1 second
            playTracks(tracks); // play the rest of the list
          }, 1000);
        };
      }
    }
    
    // start playing after the page loads
    window.onload = startMusic;
    

    音频元素可以由服务器生成。

    <audio>
        <source src="<%= $pathOfTheSound %>"></source>
    </audio>
    

    【讨论】:

    • 我可以在这个js函数中加入一个rails标签吗?
    • 不,您必须将其嵌入页面的音频元素中。您可以做的是创建一个包含音频元素 ID 的 javascript 变量。
    • 对不起,我的无知,但是 IIFE 是什么意思? TY :D
    • 一个立即调用的函数表达式,你可以查看这篇文章了解更多信息developer.mozilla.org/en-US/docs/Glossary/IIFE
    • 实际上脚本不起作用,我的意思是浏览器给了我这个错误:未捕获的类型错误:无法读取 null 的属性“播放”。脚本代码和你给我的一样,每个
    猜你喜欢
    • 2013-02-24
    • 2016-11-04
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多