Android随机播放音乐

时间:2012-05-02 11:41:59

标签: android

现在我可以在Android上播放音乐了。但我想在2到8秒之间随机播放这个声音。我怎么能随机播放它,例如第一次,它播放2秒,下一次播放7秒等等?有人能帮助我吗?

2 个答案:

答案 0 :(得分:3)

浏览以下链接:

Random number Generation

Media Player

Timer

你会得到一个想法。

答案 1 :(得分:2)

Android中的声音播放如下:

AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
int mSoundID = mSoundPool.load(this, R.raw.sound1, 1);
            float lActualVolume = (float) audioManager
                    .getStreamVolume(AudioManager.STREAM_MUSIC);
            float lMaxVolume = (float) audioManager
                    .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            float lVolume = lActualVolume / lMaxVolume;
            // Is the sound loaded already?
            if (mSoundIsLoaded) {
                mSoundPool.play(mSoundID, lVolume, lVolume, 1, 0, 1f);

我认为你已经获得了很多帮助来计算随机数。 您必须将声音文件放在assets / raw目录中。

编辑: 我忘了提到mSoundIsLoaded参数的来源。 我的声音加载后我设置了它。我在onCreate方法中这样做。当声音加载时,我设置了名为mSoundIsLoaded的布尔字段。我这样做是为了在播放声音时防止NullPointerExceptions 声音的加载看起来像这样:

mSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
            mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
                @Override
                public void onLoadComplete(SoundPool soundPool, int sampleId,
                        int status) {
                    mSoundIsLoaded = true;
                }
            });
            mSoundID = mSoundPool.load(this, R.raw.sound1, 1);
相关问题