2016-04-28 54 views
0

我想按下按钮后,我的应用程序随机播放从列表中弹出。但我在这一行中有一个问题mySounds = MediaPlayer.create (this, R.raw.myItems[n]); 如果我没有输入“R.raw.FILENAME”,我得到以下错误:“无法找到符号变量myItems”。这是我的完整代码。Android Studio - 声音与变量的路径

​​

回答

1

你可以尝试先获取该资源标识符,然后将此类创建您的媒体播放器时,像这样:

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(); 
}