简体   繁体   中英

Each item of a listView playing a different (short) media file. After so many clips I hear no more sound

I am making a sound board app. I have a String List of sound descriptions that populate the listView. My onItemClick takes in a switch statement that assigns each sound to it's string description from the list. The sounds work when the list item is clicked, but after so many clicks, all the sounds stop. the switch statement looks like this in my 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;
}

As requested a possible answer;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM