我正在开发一个应用程序,其中当一个新活动开始时,它应该开始播放声音。 所以我用mediaplayer在oncreate中播放声音,并且工作正常。 但是当我尝试使用soundpool时,通过在活动的oncreate中加载和播放它。 它不是在玩。 我选择soundpool,因为它比mediaplayer更好。
可能是什么问题? 没有soundpool在oncreate中工作?
I am working on an app, wherein when a new activity is started, it should start playing a sound. So I used mediaplayer to play the sound in oncreate and It worked fine. But when I tried to use soundpool instead, by loading and playing it in oncreate of the activity. Its is not playing. I choose soundpool, since its better than mediaplayer.
what might be the issue? doesn't soundpool work in oncreate?
最满意答案
你可以在任何地方玩,
我用一个简单的例子来证明
创建一个方法initializeSoundPool
private void initializeSoundPool(){ mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0); mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() { public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { loaded = true; } }); soundID = mSoundPool.load(this, R.raw.glassbreak, 1); }然后创建一个方法playFile
private void playFile(){ AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); float actualVolume = (float) audioManager .getStreamVolume(AudioManager.STREAM_MUSIC); float maxVolume = (float) audioManager .getStreamMaxVolume(AudioManager.STREAM_MUSIC); float volume = actualVolume / maxVolume; if (loaded) { mSoundPool.play(soundID, volume, volume, 1, 0, 1f); Log.e("Test", "Played sound"); } }然后在onCreate调用它们就像这样
private SoundPool mSoundPool; private int soundID; boolean loaded = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.spxml); initializeSoundPool(); playFile(); }或者甚至更好地调用onCreate initializeSoundPool ,然后在onResume调用playFile。
You can play it anywhere,
Ill demonstrate with a simple example
Create a method initializeSoundPool
private void initializeSoundPool(){ mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0); mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() { public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { loaded = true; } }); soundID = mSoundPool.load(this, R.raw.glassbreak, 1); }Then create a method playFile
private void playFile(){ AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); float actualVolume = (float) audioManager .getStreamVolume(AudioManager.STREAM_MUSIC); float maxVolume = (float) audioManager .getStreamMaxVolume(AudioManager.STREAM_MUSIC); float volume = actualVolume / maxVolume; if (loaded) { mSoundPool.play(soundID, volume, volume, 1, 0, 1f); Log.e("Test", "Played sound"); } }Then in onCreate call them like this
private SoundPool mSoundPool; private int soundID; boolean loaded = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.spxml); initializeSoundPool(); playFile(); }Or even better call initializeSoundPool in onCreate and then call playFile in onResume.
更多推荐
发布评论