Android - 单击按钮时播放声音 - 空指针异常 [英] Android - play sound on button click - Null pointer exception

查看:42
本文介绍了Android - 单击按钮时播放声音 - 空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过单击按钮来播放声音文件.声音只有 1 秒长.我单击按钮的前几次播放效果很好,但过了一会儿,它给出了 NullPointerException.代码如下:

I am trying to play a sound file on the click of a button. The sound is just 1 sec long. It plays well the first few times I click the button, but after a while it gives a NullPointerException. Here's the code:

button[i].setOnClickListener(new OnClickListener() {
    public void onClick(View view) {        
        mp = MediaPlayer.create(Test.this, R.raw.mysound);   
        mp.start();
    }
});

这里有一个例外:

07-29 23:07:27.690: ERROR/AndroidRuntime(10542): Uncaught handler: thread main exiting due to uncaught exception
07-29 23:07:27.710: ERROR/AndroidRuntime(10542): java.lang.NullPointerException
07-29 23:07:27.710: ERROR/AndroidRuntime(10542):     at com.example.mypackage.Test$3.onClick(Test.java:270)

推荐答案

感谢您的回答!欣赏!

这是我最终设法让它工作的方式:

Here's how I finally managed to get it work:

            button[i].setOnClickListener(new OnClickListener() {
                public void onClick(View view) {

                    mp = MediaPlayer.create(Test.this, R.raw.mysound);
                    mp.setOnCompletionListener(new OnCompletionListener() {

                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            // TODO Auto-generated method stub
                            mp.release();
                        }

                    });   
                    mp.start();
                }

            });

这篇关于Android - 单击按钮时播放声音 - 空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆