Android:第24次点击后声音无法播放

时间:2017-07-09 16:24:25

标签: java android

所以我是一个编程初学者,在制作一个带有8个按钮的简单音板应用程序时,我遇到了一个奇怪的问题,它在第24个按钮按下后停止播放声音。这是java代码:

public class MainActivity extends AppCompatActivity {

    MediaPlayer mediaPlayer;
    int i = 0;
    public void playSound(View view){

            switch(view.getId())
            {
                case R.id.button1:
                    mediaPlayer = MediaPlayer.create(this, R.raw.doyouspeakenglish);
                    break;
                case R.id.button2:
                    mediaPlayer = MediaPlayer.create(this, R.raw.goodevening);
                    break;
                case R.id.button3:
                    mediaPlayer = MediaPlayer.create(this, R.raw.hello);
                    break;
                case R.id.button4:
                    mediaPlayer = MediaPlayer.create(this, R.raw.howareyou);
                    break;
                case R.id.button5:
                    mediaPlayer = MediaPlayer.create(this, R.raw.ilivein);
                    break;
                case R.id.button6:
                    mediaPlayer = MediaPlayer.create(this, R.raw.mynameis);
                    break;
                case R.id.button7:
                    mediaPlayer = MediaPlayer.create(this, R.raw.please);
                    break;
                case R.id.button8:
                    mediaPlayer = MediaPlayer.create(this, R.raw.welcome);
                    break;
                default:
                    throw new RuntimeException("Unknown button ID");
            }
            i++;
        Log.i("klik", Integer.toString(i));
            mediaPlayer.start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

这是错误信息,我不允许发布图片作为新用户,所以这里是link

2 个答案:

答案 0 :(得分:0)

您没有发布媒体播放器资源,因此您也需要关闭并释放它们

Releasing the MediaPlayer

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/secondaryProgress">
    <shape android:shape="rectangle">
        <corners android:radius="10dp" />

        <gradient
            android:angle="270"
            android:endColor="#403F41"
            android:startColor="#403F41" />
    </shape>
</item>
<item android:id="@android:id/progress">
    <clip>
        <shape android:shape="rectangle">
            <corners android:radius="10dp" />

            <gradient
                android:angle="270"
                android:endColor="#00AEEF"
                android:startColor="#00AEEF" />
        </shape>
    </clip>
 </item>
</layer-list>

答案 1 :(得分:0)

请阅读媒体播放器上的注释:

完成MediaPlayer后,您应该调用release()来释放资源。如果没有发布,太多的MediaPlayer实例将导致异常。

所以在再次调用MediaPlayer.create之前,请调用

mediaPlayer.stop();
mediaPlayer.release();