简体   繁体   English

随机资源选择

[英]Random resource selection

I want to select certain audio files when a user presses a button but i cant seem to find how i can change the R.raw. 当用户按下按钮时,我想选择某些音频文件,但是我似乎找不到改变R.raw的方法。 so that it will change in here. 这样它就会在这里改变

I know there should be a easier sollution than creating 1000 if else with R.raw.0, R.raw.1 ,... 我知道应该比使用R.raw.0,R.raw.1,...创建1000个方法更容易。

So in my example i have selected file "c.mp3" but this must be eventualy change to 000 till 499. So random (or selective) say 050 => this shoud become R.raw.050 因此,在我的示例中,我选择了文件“ c.mp3”,但最终必须将其更改为000,直到499。因此,随机(或选择性)说050 =>这个应该变成R.raw.050。

}

@Override
public void play() {

    final MediaPlayer mp = MediaPlayer.create(context, R.raw.c);
    mp.start();

}

You can try using: 您可以尝试使用:

context.getResources().getIdentifier("050", "raw", this.getPackageName());

and randomize the name ("050") using a Random object instance. 并使用随机对象实例将名称(“ 050”)随机化。

Let's say that you have your random number like this : 假设您有这样的随机数:

String rand = "050";

It is easy you need just to find the raw resource id and pass it to your MediaPlayer.create method like that : 您只需找到原始资源ID并将其传递给您的MediaPlayer.create方法即可,就像这样:

int rawResourceId = context.getResources().getIdentifier(rand, "raw", this.getPackageName());

final MediaPlayer mp = MediaPlayer.create(context, rawResourceId);
mp.start();

Suggestion : 建议:

  • It's better to rename your resources files by prefixing them by a letter like f_000 , f_001, ...., f_050. 最好使用前缀f_000,f_001,....,f_050之类的字母来重命名资源文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM