2016-04-28 62 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(); 
}