【发布时间】:2021-09-16 07:17:28
【问题描述】:
这是我的第一个 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:无法加载样本:(null)”。
请让我知道我的代码在哪里出错并进行修复。提前致谢。
【问题讨论】:
-
我将 audioAttributes
.USAGE_ASSISTANCE_SONIFICATION更改为 '.USAGE_MEDIA`。然后使用大小小于 40KB 的 mp3 文件代替 ogg 文件。当我运行调试器时,soundPool 工作但实际运行它不会。是不是因为下一个代码语句正在导航到另一个片段。如何解决这个问题?谢谢。