【问题标题】:Javascript if/else statement that plays an mp3 audio file [duplicate]播放mp3音频文件的Javascript if/else语句[重复]
【发布时间】:2016-02-16 20:13:51
【问题描述】:

我正在尝试用 JavaScript 编写 if/else 语句,当条件为真时播放 mp3 音频文件。我只是希望它在没有按钮的情况下开始播放,就像我在这里看到的其他一些代码一样。 这是我目前所拥有的一个例子。

  var name = function(code) {
    if('Hi.'){
        console.log("Hello.");}
        //This is where I want to add an audio file

    else if('Good morning.'){
        console.log("How are you today?");}
        //This is also where I want to add a file

【问题讨论】:

    标签: javascript audio


    【解决方案1】:

    这会发出一些声音。您必须将声音文件放在同一文件夹中。

    var sound1 = new Audio('file1.mp3'); 
    var sound2 = new Audio('file2.mp3');
    

    然后运行添加了音频的 if/else。

    var name = function() {
        if('Hi.'){
            console.log("Hello.");
            sound1.play();
        }
        else if('Good morning.'){
            console.log("How are you today?");
            sound2.play();
        }
    }
    

    如果您希望它刚刚开始运行,只需将函数 name() 添加到代码底部即可。

    name();
    

    这将运行函数。

    【讨论】:

      【解决方案2】:
      function playAudio(filename) {
      
          var audio = document.createElement("audio");
          audio.preload = "auto";
      
          var src = document.createElement("source");
          src.src = filename + ".mp3";
          audio.appendChild(src);
      
          audio.load();
          audio.currentTime = 0.01;
          audio.volume = 1;
      
          //Due to a bug in Firefox, the audio needs to be played after a delay
          setTimeout(function () {
              soundFile.play();
          }, 1);
      }
      
      var name = function (code) {
          if ('Hi.') {
              playAudio("audio.mp3");
          } else if ('Good morning.') {
              console.log("How are you today?");
          }
          playAudio("audio.mp3");
      } else {
          //other
      }
      

      【讨论】:

        猜你喜欢
        • 2014-01-04
        • 2016-11-21
        • 1970-01-01
        • 2018-01-29
        • 1970-01-01
        • 1970-01-01
        • 2020-10-25
        • 2020-11-29
        • 2021-09-11
        相关资源
        最近更新 更多