2017-04-05 86 views
0

我正在創建一個使用http請求從服務器加載.mp3文件的離子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.e.所有的值都在聲音數組中得到更新。首先通過'console.log()'檢查'console'。如果是,那麼在點擊播放這些聲音的隨機聲音時創建一個按鈕很容易?使用'Math.floor(Math.random()* sounds.length());'創建一個隨機索引。 –

+0

@SagarKulkarni我已經有一個按鈕,當點擊播放聲音(我在我的問題中添加了代碼) 我在哪裏添加您建議的代碼? –

回答

0

所以,這裏是HTML您隨機按鈕:

<button (click)="playRandom()">Random Sound</button> 

在你的.ts:

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

而這應該工作。

+0

如果無法按預期工作,請通過調試解決代碼中的其他問題。另外,這只是一個模板代碼。根據需要調整按鈕的樣式。 –

+0

薩加爾,你有Skype嗎? –

+0

試試看,讓我知道問題出在哪裏。爲什麼我們需要Skype? –