2017-02-21 53 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