我正在制作一个声卡应用程序。我有一个填充listView的声音描述的字符串列表。我的onItemClick接受一个switch语句,它从列表中为每个声音分配它的字符串描述。单击列表项时声音有效,但经过这么多次点击后,所有声音都会停止。 switch语句在我的ItemOnClick中显示如下:
switch (soundName){
case "magic whoosh":
mediaPlayer = MediaPlayer.create(context, R.raw.magic_whoosh);
mediaPlayer.start();
break;
case "magic poof":
mediaPlayer = MediaPlayer.create(context, R.raw.magic_poof);
mediaPlayer.start();
break;
}
答案 0 :(得分:0)
根据要求提供可能的答案;
//declare instance variable
static MediaPlayer mediaPlayer;
//handle listview on item click
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(mediaPlayer==null){
mediaPlayer=new MediaPlayer();
try{
mediaPlayer.setDataSource(//datasource based on position);
mediaPlayer.prepare(); //this uses the same UI thread
mediaPlayer.start();
}catch(Throwable e){
//handle possible errors
}
}else{
if(mediaPlayer.isPlaying())mediaPlayer.stop();
mediaPlayer.reset();
try{
mediaPlayer.setDataSource(//datasource based on position);
mediaPlayer.prepare(); //this uses the same UI thread
mediaPlayer.start();
}catch(Throwable e){
//handle possible errors
}
}
}
});