【问题标题】:Play a random song on button press using Javascript使用 Javascript 在按下按钮时播放随机歌曲
【发布时间】:2021-02-27 06:06:12
【问题描述】:

我将一些 HTML 代码设为一个函数,以便在单击按钮时运行 randomSong(),它现在应该运行一首随机歌曲,它运行以下代码:

function randomSong() {
    var n = (1 + Math.random() * 2);
    if (n == 0){
        var song = document.getElementById('1')
        console.log("0")
    }else if(n == 1){
        var song = document.getElementById('2');
        console.log('1')}
    let y = song
}
var x = y

function playAudio() {
    x.play();
}

function pauseAudio() {
    x.pause();
}

但它不起作用它说现在没有人定义 x 为什么? Link to the website I am using this for

【问题讨论】:

    标签: javascript html function random


    【解决方案1】:

    我试过你的演示它说y is not defined,因为当你尝试访问y的外部范围时。

    你可以这样尝试:

    var x;
    
    function randomSong() {
        var n = (1 + Math.random() * 2);
        var song;
        if (n === 0){
            song = document.getElementById('1')
            console.log("0")
        }
        else if(n === 1){
            song = document.getElementById('2');
            console.log('1')
        }
        x = song;
    }
    
    function playAudio() {
        if(x){
            x.play();
        }
    }
    
    function pauseAudio() {
        if(x){
            x.pause();
        }
    }
    

    【讨论】:

      【解决方案2】:

      如果这不起作用,您需要提供更多代码。我所做的只是修复一些明显的错误。具体来说,n ==enter code here 0 更改为 n==0var x = y;,其中 y 不是全局变量 y 现在是全局变量。如果这没有帮助添加更多代码,我会看看我是否可以解决它。

      var y;
      function randomSong() {
        var n = (1 + Math.random() * 2);
        if (n == 0) {
          var song = document.getElementById('1')
          console.log("0")
        } else if (n == 1) {
          var song = document.getElementById('2');
          console.log('1')
        }
         y = song;
      }
      var x = y;
      
      function playAudio() {
        x.play();
      }
      
      function pauseAudio() {
        x.pause();
      }

      【讨论】:

        【解决方案3】:
        let x;
        
        function randomSong() {
          const n = (1 + Math.random() * 2);
          let song;
          if (n === 0) {
            song = '0'
            console.log("0");
          }else if (n === 1) {
            song = '1';
            console.log('1');
          } else {
            song = '999';
            console.log('999');
          }
          x = song;
        }
        
        function playAudio() {
          console.log(`${x} play`);
        }
        
        function pauseAudio() {
          console.log(`${x} pause`);
        }
        
        randomSong();
        playAudio();
        pauseAudio();
        

        如果没有必要使用var,不建议使用var

        【讨论】:

          【解决方案4】:

          letconstclass 引入的标识符是块范围的。因此在

              else if(n == 1){
                   var song = document.getElementById('2');
                   console.log('1')}
                   let y = song
              }
              var x = y
          

          let y = song 创建的 y 变量在分配给 x 时不在范围内

             var x = y
          

          如果对x 的赋值继续进行而没有产生错误,这可能意味着y 的先前定义,可能在范围内具有undefined。这是自动输入会产生的陷阱:

          不要自动在对外部作用域变量的赋值前面加上letconst,否则赋值将不会发生。

          【讨论】:

            【解决方案5】:

            我查看了您的网站,我注意到当您单击 单击此处查看推荐歌曲 时,它会调用函数 num(),因此会显示带有建议曲目的警报。所以把它变成你想要的。当我们点击按钮时,我们必须调用函数 randomSong 和带有注释说明的代码:

            var song = null;
            function randomSong() {
                //to get audio's number dynamically.
                let n = document.querySelectorAll('p audio').length;
                //grab all audios from HTML Node List to an array.
                let audios = [...document.querySelectorAll('p audio')];
                //if there is another song singing ! we should stop it
                if(song!==null)    song.pause();
                //we pick randomly a song inside the array of audios.
                song = audios[ Math.floor ( Math.random() * n) ];
                //and then we play the song, Enjoy listening!
                song.play();
            }
            

            【讨论】:

              【解决方案6】:

              谢谢大家的回答,但我找到了一个更好/更简单的方法来做到这一点,javascript是

               var songList = [
              'mp3_url',
              'mp3_url',
              'mp3_url',
              'mp3_url',
              'mp3_url',
                  ];
              //this gets a random url from the list
              function randomChoice(choices) {
                var index = Math.floor(Math.random() * choices.length);
                return choices[index];
              }
              //this is just a place holder you can change this function to anything
              function age(){
                let current = new Date().getTime();
                var myAge = current - 1151560800000;
                var myAge = myAge/1000
                return myAge;
              }
              /*this trys to pause x and then play a new song but if x is not defined then you 
              get an error so you have to do try catch finally*/
                function playAudio() {
                try{x.pause();}catch(err){
                  var old = age();
                  var years = old / 31536000;
                  console.log('Hello I was ' + old + ' seconds (' + years + ' years) old when you clicked that button!');}finally{
                  x = randomChoice(songList);
                x = new Audio(x);
                x.play();
                }};
              function pauseAudio() {
                  x.pause();
                }
              

              HTML 是这样的

              <button onclick="playAudio()">play a song</button>
              <button onclick="pauseAudio()">pause the current song</button>
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多