Hello everyone! Search used, but did not find a solution. In general: There is an array of tunes, such a plan:

mediaPlayers[0] = MediaPlayer.create(getActivity(), R.raw.a); 

Only 7 el. Array. And there are 7 imageview, which are also in the array

 arr_imageB[0] = (ImageView) rootViewB.findViewById(R.id.b1); 

And here's the problem: I click on imageview [i], everything is played, All melodies are played, but when I select the previous imageview, I’m logging a message:

Call this method to stop the previous melody:

 private void stopPlayerIfNeeded() { for (int i = 0; i < mediaPlayers.length; i++) { MediaPlayer mediaPlayer = mediaPlayers[i]; if (mediaPlayer.isPlaying()) { mediaPlayer.stop(); mediaPlayer.reset(); } } } 

Call example:

  case R.id.b7: arr_imageB[6].setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Animation anim = AnimationUtils.loadAnimation(v.getContext(),R.anim.clickbutton); arr_imageB[6].startAnimation(anim); stopPlayerIfNeeded(); mediaPlayers[6].start(); 

The warning also hangs: Should have subtitle controller already set

    1 answer 1

    For good, you need to use one media player, when you click on the imageView, change the dataSource. The error occurs because you started playing before the player is ready to play it.

     mp.setDataSource(url); mp.setOnPreparedListener(this); mp.prepareAsync(); public void onPrepared(MediaPlayer player) { player.start(); } 

    try using one media player, your logic will be simplified

      private void stopPlayerIfNeeded() { if (mediaPlayer.isPlaying()) { mediaPlayer.stop(); } } 

    when you click on imageView, call

     if (mediaPlayer.isPlaying()) { mediaPlayer.stop(); } else { mediaPlayer.setDataSource(context, uri);// новый трэк mediaPlayer.prepareAsync(); //после того как плеер будет готов к проигрыванию, сработает коллбэк onPrepared(), описанный выше, и трэк начнет играть } 
    • Thank you! Please tell me how to implement it in my class: pastebin.com/iFJUjaf0 - upward
    • one
      I refactored a bit of pastebin.com/q47LmWmd . But I left todo, you have one copy-paste there, for good, your fragment can be placed in a maximum of 200 lines instead of 600 if you get rid of copy - paste - Yury Pashkov
    • I will remove kopipast, I think that in cycles or methods, And then call. or how best to do, please tell me? I know that if something is used in the code more than 2 times, then you need to write a method. Thank you - upward
    • Sorry, I wanted to clarify: linLayout.setBackgroundColor (Color.parseColor ("# DD000000")); is it possible to replay melodies change the background to color - upward