This is my first Android app. Java is new to me.
I am trying to use SoundPool but the sound file is not getting loaded. In the Button.setOnClickListener method in a fragment, trying to play a sound strip, but it is not working.
I did some research on this issue by browsing internet including this website. Could not get correct reasons for failure and a fix.
My code is as follows:
public class LauncherFragment extends Fragment {
private FragmentLauncherBinding binding;
SoundPool soundPool;
int launcher ;
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
binding = FragmentLauncherBinding.inflate(inflater, container, false);
if (Build.VERSION.SDK_INT
>= Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes
audioAttributes
= new AudioAttributes
.Builder()
.setUsage(
AudioAttributes
.USAGE_ASSISTANCE_SONIFICATION)
.setContentType(
AudioAttributes
.CONTENT_TYPE_SONIFICATION)
.build();
soundPool
= new SoundPool
.Builder()
.setMaxStreams(3)
.setAudioAttributes(
audioAttributes)
.build();
}
else {
soundPool
= new SoundPool(
3,
AudioManager.STREAM_MUSIC,
0);
}
try {
launcher
= soundPool
.load(
getActivity().getApplicationContext(),
R.raw.soundbite_mpthree,
1);
}
catch ( Exception e)
{
Toast.makeText(LauncherFragment.this.getContext(), "Load failed", Toast.LENGTH_SHORT).show();
}
return binding.getRoot();
}
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
binding.launcherButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
soundPool.play(
launcher, 1, 1, 0, 0, 1);
soundPool.autoPause();
NavHostFragment.findNavController(LauncherFragment.this)
.navigate(R.id.action_LauncherFragment_to_ActionFragment);
}
});
}
During debugging, I found the value of launcher to be 1 and debugger console messaged "E/SoundPool: Unable to load sample: (null)".
Please let me know where my code is wrong and fix for the same. Thanks in advance.
The solution I found was making following changes to the code.
.USAGE_ASSISTANCE_SONIFICATION to '.USAGE_MEDIA.handler.post(new Runnable(){ //code to play sound handler.postDelayed(); to introduce some delay for soundpool to complete its job });I do not know how solution 1 and 2 resolved loading sound file. But it worked.