2017-04-16 11 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.random()* sound.file。 'rand'は1つの要素を持つ配列に初期化されていますか? –

答えて

1

。あなたの問題の説明に基づいて、私はあなたが私はこれらの一般的な機能のために、「underscorejs」ライブラリを使用することが常に優れていると感じ

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"を達成できます。

import * as _ from 'underscore'; 

getRandomElementFromArray (sounds) { 
    let randomNumber = _.random(0, sounds.length); 
    return sounds[randomNumber]; 
} 
関連する問題