[英]Android: OnClick play random .mp3 from /res/raw file
我是Android應用程序開發的新手,我正在嘗試從/ res / raw文件夾播放隨機的.mp3。
已修正到目前為止,但是我遇到了FileNotFoundException。
已修正僅在第一次點擊時播放隨機的聲音,此后除非重新打開應用程序,否則它是相同的聲音。
新問題現在播放隨機聲音,但是當我多次單擊按鈕時,聲音會同時開始播放,並且仍然在日志中顯示“ start()mUri為null”消息。
更新的代碼
MediaPlayer player;
int soundIndex;
AssetFileDescriptor descriptor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* gets a random index from an array of sounds
*
* @return
*/
public int getRandomSoundIndex(){
int soundIndex;
int[] sound = SOUNDZ;
Random random = new Random();
soundIndex = random.nextInt(sound.length);
return sound[soundIndex];
}
/**
* Plays that random sound on button click
* @param button
*/
public void playRandomSound(View button){
//where button is physically located
button = (Button) findViewById(R.id.button1);
//get random sound index
soundIndex = getRandomSoundIndex();
//make media player
player = MediaPlayer.create(this, soundIndex);
//play sound
player.start();
}
這是日志:
09-21 17:42:32.528:D / MediaPlayer(4282):start()mUri為空
您在這里遇到一些問題。
首先,在Field
上調用toString()
將為您提供對象實例的字符串表示形式,例如"public static final int com.lena.button.R$raw.laptopkeyboard1"
,這不是很有用。 想必您需要getInt()
。
其次,原始資源不是資產,因此您不要使用openFd()
。 而是使用靜態create()
方法創建MediaPlayer
實例,並將您從getInt()
獲得的int
傳遞到Field
。
第三,反思很慢。 請不要重復一次。 一次使用R.raw.class.getFields()
,將結果緩存。 或者,更好的是,考慮根本不使用反射,而是使用自己的文字Java int[]
:
static int[] SOUNDZ={R.raw.boom, R.raw.chaka, R.raw.laka};
(當然,用您自己的聲音資源代替)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.