这是我的第一个Android应用。Java对我来说是新的。
我正在尝试使用SoundPool,但无法加载声音文件。在Button.setOnClickListener方法中的一个片段中,试图播放一个声音条,但它不起作用。
我通过浏览互联网,包括这个网站,对这个问题做了一些研究。无法获取正确的失败原因和修复。
我的代码如下:
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);
}
});
}在调试过程中,我发现launcher的值为1,调试器控制台显示消息"E/SoundPool: Unable to load sample:(null)“。
请让我知道我的代码是错误的,并解决同样的问题。提前谢谢。
发布于 2021-09-24 12:42:32
我找到的解决方案是对代码进行以下更改。
使用.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 });我不知道解决方案1和2如何解决加载声音文件。但它成功了。https://stackoverflow.com/questions/69203940
复制相似问题