我想按按钮后我的应用程序从列表中随机播放曲目。但是这行mySounds = MediaPlayer.create (this, R.raw.myItems[n]);有问题
如果不输入“R.raw.FILENAME”,则会出现以下错误:“找不到符号变量myItems”。这是我的完整代码。

MediaPlayer mySounds;
public void Play_sound(View v) {
    Random rand = new Random();
    int n=rand.nextInt(2);
    String[]myItems={"itemA","itemB"};
    mySounds = MediaPlayer.create(this, R.raw.myItems[n]);
    mySounds.start();
}

最佳答案

您可以尝试先获取资源标识符,然后在创建媒体播放器时将其传递进来,如下所示:

MediaPlayer mySounds;
public void Play_sound(View v) {
Random rand = new Random();
int n=rand.nextInt(2);
String[]myItems={"itemA","itemB"};
//this line added to get the id of the random item
int randomSoundId = getResources().getIdentifier(myItems[n], "raw", getPackageName());
//then give this id to the MediaPlayer
mySounds = MediaPlayer.create(this, randomSoundId);
mySounds.start();
}

关于android - Android Studio-声音可变的路径,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36919147/

10-11 15:17