可以在onCreateView()中播放SoundPool类吗?

时间:2016-09-26 08:07:32

标签: android android-studio fragment soundpool

我正在开发一款应用,其中当启动新片段时,它应该开始播放声音。所以我使用soundpool在onCreateView中播放声音,但不能正常工作。可能是什么问题?没有soundpool在onCreateView中工作?

这是我的代码

    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.next_ex, container, false);

    createSoundPool();
    loadSounds();
    volumeSounds();

    mSoundPool.play(sdID_clock,volume/2,volume/2,0,0,1);

    return rootView;
}

protected void createSoundPool(){

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mAttributesBuilder = new AudioAttributes.Builder();
        mAttributesBuilder.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION);
        mAttributesBuilder.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION);
        mAttributes = mAttributesBuilder.build();

        mSoundPoolBuilder = new SoundPool.Builder();
        mSoundPoolBuilder.setAudioAttributes(mAttributes);
        mSoundPool = mSoundPoolBuilder.build();
    } else {
        mSoundPool = new SoundPool(10, AudioManager.MODE_IN_COMMUNICATION,0);
        mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            public void onLoadComplete(SoundPool soundPool, int sampleId,
                                       int status) {
                loaded = true;
            }
        });
    }

}

protected void loadSounds(){
    sdID_clock = mSoundPool.load(getContext(), R.raw.clock,1);
}

protected void volumeSounds(){
    getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);
    audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
    curVolume = (float)audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    maxVolume = (float)audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

    volume = curVolume / maxVolume;
}

1 个答案:

答案 0 :(得分:2)

是的,你可以。从异步线程调用这些方法。

createSoundPool();
loadSounds();
volumeSounds();

然后覆盖setOnLoadCompleteListener以确保在播放之前加载了soundpool。