Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/432.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Javascript在按下按钮时播放随机歌曲_Javascript_Html_Function_Random - Fatal编程技术网

使用Javascript在按下按钮时播放随机歌曲

使用Javascript在按下按钮时播放随机歌曲,javascript,html,function,random,Javascript,Html,Function,Random,我将一些HTML代码设置为一个函数,这样当单击一个按钮时,它会运行randomSong(),现在应该运行一首随机歌曲,它会运行以下命令: 函数randomSong(){ var n=(1+Math.random()*2); 如果(n==0){ var song=document.getElementById('1') 控制台日志(“0”) }else如果(n==1){ var song=document.getElementById('2'); console.log('1')} 让y=歌曲 }

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

函数randomSong(){
var n=(1+Math.random()*2);
如果(n==0){
var song=document.getElementById('1')
控制台日志(“0”)
}else如果(n==1){
var song=document.getElementById('2');
console.log('1')}
让y=歌曲
}
变量x=y
函数playAudio(){
x、 play();
}
函数pauseAudio(){
x、 暂停();
}
但它不起作用,它说x现在没有定义,为什么?

我试过你的演示,它说
y没有定义
,因为当你尝试访问
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();
    }
}

如果这不起作用,你需要提供更多的代码。我所做的只是纠正一些明显的错误。具体来说,
n==在此处输入代码0
更改为
n==0
var x=y
其中
y
不是全局变量
y
现在是全局变量。如果这没有帮助添加更多的代码,我将看看我是否可以解决它

vary;
函数randomSong(){
var n=(1+Math.random()*2);
如果(n==0){
var song=document.getElementById('1')
控制台日志(“0”)
}else如果(n==1){
var song=document.getElementById('2');
console.log('1')
}
y=歌曲;
}
var x=y;
函数playAudio(){
x、 play();
}
函数pauseAudio(){
x、 暂停();
}
让x;
函数randomSong(){
常数n=(1+Math.random()*2);
让歌声;
如果(n==0){
宋='0'
控制台日志(“0”);
}else if(n==1){
宋='1';
console.log('1');
}否则{
宋='999';
控制台日志('999');
}
x=歌曲;
}
函数playAudio(){
log(`${x}play`);
}
函数pauseAudio(){
log(`${x}pause`);
}
随机歌曲();
播放音频();
pauseAudio();

如果不需要使用
var
const
class
引入的标识符是块范围的,则不建议使用
var
。因此

    else if(n == 1){
         var song = document.getElementById('2');
         console.log('1')}
         let y = song
    }
    var x = y
当分配给
x
时,由
let y=song
创建的
y
变量不在范围内

   var x = y
如果对
x
的赋值没有产生错误,则可能意味着先前定义的
y
,可能是
未定义的
值在范围内。这是一个自动键入可以产生的陷阱:


不要自动使用
let
const
将赋值置于外部作用域变量之前,否则赋值将不会发生。

我查看了您的站点,我注意到当您单击单击此处获取建议歌曲时,它会调用函数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();
}

谢谢大家的回答,但我找到了一个更好的/eaiser方法,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>
播放一首歌
暂停当前歌曲