2016-09-26 42 views
0

我正在开发一个应用程序,其中当一个新的Fragment启动时,它应该开始播放声音。所以我使用soundpool在onCreateView中播放声音,但不工作。可能是什么问题?在onCreateView中不工作?可以在onCreateView()中播放SoundPool类吗?

这是我的代码

@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; 
} 
+0

你应该调用createSoundPool(); volumeSounds(); –

回答

2

当然可以。从异步线程调用这些方法。

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

然后覆盖setOnLoadCompleteListener,确保soundpools打他们之前被加载。