2017-02-21 54 views
0

我使用DB瀏覽器創建了一個DB sqlite。 我需要從我的Db開始隨機化音頻。 該表是「音頻」與4場(Id,音頻,col2,col3) 我把「音頻」字段R.raw.nameaudio。我自己DB的隨機聲音

這是隨機數:

 rand = new Random(); 
     int random=rand.nextInt(4)+1; 

這是查詢:

public Cursor cont(Integer ID){ 
    SQLiteDatabase db = this.getWritableDatabase(); 
    Cursor res = db.rawQuery("select audio from audio where ID= "+ID, null); 
    return res; } 

現在我要開始的MediaPlayer,但它不工作。

這是代碼的其餘部分:

 Cursor res = mDBHelper.controllo(random); 
        while (res.moveToNext()) { 
         int audio = res.getInt(0); 
         stopPlaying(); 
      mp = MediaPlayer.create(getApplicationContext(),audio); 
         mp.start(); 

        } 

沒有與mediaplayer.create的第二個參數的問題。 我不能傳遞正確的數據類型。我如何解決這個問題?

非常感謝。

編輯: 我試着只把「nameaudio」放在「audio」字段中。我插入後:

   int audio = getResources().getIdentifier(res.getString(0), 
                "raw", "mypackage"); 
               stopPlaying(); 

        mp = MediaPlayer.create(getApplicationContext(),audio); 
         mp.start(); 

現在我listn的音頻,但一些後點擊應用程序崩潰。

+0

爲什麼不選擇一個隨機行? '... ORDER BY RANDOM LIMIT 1' –

+0

嘗試「int audio = res.getInt(1);」因爲你說你有4個字段(Id,audio,col2,col3),所以「audio」在索引「1」上。 –

+0

@Rotwang你是對的,但問題仍然存在,我需要消除聲音開始後的行。 – Scar

回答

0

獲得隨機數

嘗試是這樣的:

int aud1 = R.raw.my_audio_1; 
    int aud2 = R.raw.my_audio_2; 
    int aud3 = R.raw.my_audio_3; 
    int aud4 = R.raw.my_audio_4; 

    int audioToPlay = -1; 
    switch (random){ 
     case 1: 
      audioToPlay = aud1; 
      break; 
     case 2: 
      audioToPlay = aud1; 
      break; 
     case 3: 
      audioToPlay = aud1; 
      break; 
     case 4: 
      audioToPlay = aud1; 
      break; 
    } 
    // now simply assign this audio to media player 

    mp = MediaPlayer.create(getApplicationContext(),audioToPlay); 
    mp.start(); 
+0

我需要DB解決方案,因爲我有100或更多的聲音。 – Scar