When I try to call the loadSound method inside setOnClickListener , the sound does not appear, but when I call it in the onCreateView or onStart , then the sound appears and everything works fine.
What is the problem here and is there any way to call the method only by pressing the buttons?

and even I called the setOnLoadCompleteListener method inside the setOnClickListener and still did not help.

 public class InsectsFragment extends Fragment { private View view; private int mBeeSound; public InsectsFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view= inflater.inflate(R.layout.fragment_insects, container, false); Sound.mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() { @Override public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { Sound.loaded = true; } }); ImageButton beeBtn = (ImageButton) view.findViewById(R.id.imageButtonBee); beeBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (Sound.mStreamID > 0) { Sound.mSoundPool.stop(Sound.mStreamID); } mBeeSound = Sound.loadSound(getContext(), "bee.mp3"); if (Sound.loaded) { Sound.playSound(mBeeSound); Snackbar.make(view, R.string.Bee, Snackbar.LENGTH_SHORT).show(); Toast.makeText(view.getContext(), R.string.Bee, Toast.LENGTH_SHORT).show(); } } }); return view; } 

    1 answer 1

    Most likely the fact is that you are trying to start playback before the end of its download. Those. you need to start the sound download in onClick, install the ending listener and start the playback in it. The code did not test what I don't know about Sound , but it should look something like this:

     @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view= inflater.inflate(R.layout.fragment_insects, container, false); ImageButton beeBtn = (ImageButton) view.findViewById(R.id.imageButtonBee); beeBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (Sound.mStreamID > 0) { Sound.mSoundPool.stop(Sound.mStreamID); } Sound.mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() { @Override public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { Sound.loaded = true; if (Sound.loaded) { Sound.playSound(mBeeSound); Snackbar.make(view, R.string.Bee, Snackbar.LENGTH_SHORT).show(); Toast.makeText(view.getContext(), R.string.Bee, Toast.LENGTH_SHORT).show(); } } }); mBeeSound = Sound.loadSound(getContext(), "bee.mp3"); return view; } 

    And format the code in question - it is very difficult to figure it out in this form.