2017-04-05 11 views
0

httpリクエストを使用してサーバーから.mp3ファイルをロードするionic 2サウンドボードアプリケーションを作成しています。 mp3はsoundboard.htmlページにボタンの形で表示されます。httpリクエスト(Ionic 2)を使用してランダム音声を再生

私がしようとしているのは、クリックしたときにというランダムな機能を呼び出すボタンを作成することです。はmp3ファイルを再生します。

私は解決策が簡単だと思います。これを行う方法については何も考えていません。

soundboard.ts

constructor(public http: Http) { 
    this.http.get(this.base_url + this.sounds_url) 
     .subscribe(
     data => { 
      /* Create a webpage out of the data from the http.get request */ 
      let content: string = data.text(); 
      let doc: any = document.createElement("html"); 
      doc.innerHTML = content; 

      /* Extract all "a" tags from it */ 
      let links: any = doc.getElementsByTagName("a"); 

      /* Loop through them, saving their title and sound file */ 
      for(let link of links) {    
      let filename = link.getAttribute("href") 

      this.sounds.push({ 
       title: link.innerHTML, 
       file: filename 

      }); 
      } 
     }, 
     err => console.error('There was an error: ' + err), 
     () => console.log('Get request completed') 
     ); 
    } 


/* Plays a sound, pausing other playing sounds if necessary */ 
    play(sound) { 
    console.log(sound) 
    if(this.media) { 
     this.media.pause(); 
    } 
    this.media = new Audio(sound.file); 
    this.media.load(); 
    this.media.play(); 
    } 

soundboard.html

<ion-grid> 
    <ion-row wrap> 
    <ion-col ng-repeat *ngFor="let sound of sounds" width-33> 
    <ion-card> 
    <ion-card-content (click)="play(sound)">   
     <img src="{{ sound.imageUrl }}" /> 
    </ion-card-content> 
    </ion-card> 
    </ion-col>  
    </ion-row> 
</ion-grid> 
+0

上記のコードは正しく動作していますか? –

+0

I.すべての値がサウンドアレイで更新されています。 'console.log()'で 'console'を最初にチェックしてください。はいの場合は、これらのサウンドのランダムなサウンドをクリックしてクリックしてボタンを作成するのは簡単ですか?ランダムなインデックスを作成するには、 'Math.floor(Math.random()* sounds.length());'を使用します。 –

+0

@SagarKulkarniクリックしたときに音が鳴るボタンが既にあります(私の質問にコードを追加しました) 提案したコードはどこに追加しますか? –

答えて

0

だから、ここにあなたのランダムボタンがHTMLである:

あなた.TSで
<button (click)="playRandom()">Random Sound</button> 

playRandom(){ 
    var index = Math.floor(Math.random() * sounds.length()); 
    play(sounds[index]); 
} 

これはうまくいくはずです。

+0

期待どおりに動作しない場合、デバッグを介してコードの周りに他のものを回避してください。また、これは単なるテンプレートコードです。必要に応じてボタンのスタイルを設定します。 –

+0

Sagar、スカイプはありますか? –

+0

これを試して、どこに問題があるか教えてください。なぜスカイプが必要なのですか? –

関連する問題