声音在Lollipop上工作但在kitkat或旧版本上没有

时间:2015-08-24 14:13:15

标签: java android soundpool

我制作了一个我在onCreate中使用的方法,它被称为loadSounds,根据版本,我使用SoundPool Builder或弃用的版本(如果它是旧版本的Android)。 .....但声音只适用于Lollipop设备......可能出错......应用程序在两个版本中运行.....持有SoundPool的变量在onCreate之外声明为object属性private static SoundPool mySounds;

提前致谢!!!

private void loadSounds(){

        if(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP) {

            AudioAttributes audioAttributes = new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN).setUsage(AudioAttributes.USAGE_GAME).build();

            mySounds = new SoundPool.Builder().
                    setMaxStreams(10).
                    setAudioAttributes(audioAttributes).
                    build();

            correctAnswerID = mySounds.load(this, R.raw.correctanswer, 1);
            incorrectAnswerID = mySounds.load(this, R.raw.incorrectanswer, 1);
        }
        else
        {
            mySounds= new SoundPool(10, AudioManager.USE_DEFAULT_STREAM_TYPE,1);
            correctAnswerID = mySounds.load(this, R.raw.correctanswer, 1);
            incorrectAnswerID = mySounds.load(this, R.raw.incorrectanswer, 1);

        }

    }

使用声音的方法是(如果答案是正确的,则播放正确的mp3,否则播放错误的mp3):

if(selectedAnswer.equals(currentAnswer) || isEnharmonic ){

            correctAnswers+=1;
            reproduceAnswerSound("Correct");

        }
        else
        {
            incorrectAnswers+=1;
            reproduceAnswerSound("Incorrect");


        }

和重现声音的方法是这样的:

private void reproduceAnswerSound(String type){



        if(type.equals("Correct")){

           mySounds.play(correctAnswerID,1,1,1,0,1);


        }else if(type.equals("Incorrect"))
        {
            mySounds.play(incorrectAnswerID,1,1,1,0,1);

        }

    }

0 个答案:

没有答案