2017-04-16 60 views
0

我正在创建一个音板,当单击一个按钮时它会播放随机声音。我试图通过在获取所有mp3文件链接(文件名)的for循环中创建数组来完成此操作,并且当用户单击按钮时使用(Math.floor(Math.random))更改文件名称。从for循环获取随机值(角度2)

我遇到的问题是,它只是发挥相同的声音。它不会播放随机声音。

soundboard.ts

/* Loop through them, saving their title and sound file */ 
      for(let link of links) { 
      let filename = link.getAttribute("href")    
      let rand = [filename]; 
      this.sounds.push({ 
       file: filename, 
       rand: rand 
      }); 
      } 

    /* Plays the sound */ 
     play(sound) {  
      sound.rand = sound.file[Math.floor(Math.random() * sound.file.length)]; 
      console.log(sound.rand) 
      this.media = new Audio(sound.rand); 
      this.media.load(); 
      this.media.play(); 
     } 
+0

您的代码很难阅读。你在错误的地方有类型。 'let rand:any = [filename];'是_terrible_代码。另一方面,'play(sound){'实际上可以使用类型注释.... –

+0

无论如何,你是不是指'const randomSound = sounds [Math.floor(Math.random()* sound.file。 ''this.media = new Audio(randomSound);'为什么'rand'初始化为一个元素的数组? –

回答

1

似乎有一个逻辑错误。根据你的问题描述,我认为你想要类似于

export class Component { 
    soundFileNames: string[] = []; 

    media?: Audio; 

    ngOnInit() { 
    for (const link of links) { 
     const fileName = link.getAttribute("href"); 
     soundFileNames.push(fileName);  
    } 
    } 

    playRandomSoundFile() { 
    const randomIndex = Math.floor(Math.random() * soundFileNames.length); 
    const randomFileName = soundFileNames[randomIndex]; 
    console.log(randomFileName); 
    const audio = new Audio(randomFileName); 
    audio.load(); 
    audio.play(); 
    this.media = audio; 
    } 
} 
+0

像一个魅力工作,谢谢 –

-1

我觉得使用“underscorejs”库对于这些常用功能总是更好。在你的情况下,你试图从数组中获得随机值,你可以通过下面的“underscorejs”来实现。

import * as _ from 'underscore'; 

getRandomElementFromArray (sounds) { 
    let randomNumber = _.random(0, sounds.length); 
    return sounds[randomNumber]; 
}