1

我有一个应用程序可以替换图像并在单击按钮时播放声音,我要做的是在声音停止播放后恢复到原始图像。

我的按钮点击监听器:

    public void onClick(View v) {
        // Perform action on click
        Context context = getApplicationContext();
        CharSequence text = "Playing Theme";
        int duration = Toast.LENGTH_SHORT;

            //this is the replaced image while the sound is playing
        imgSheep.setImageResource(R.drawable.replacedimage);

        Toast.makeText(context, text, duration).show();
        playSound(R.drawable.sound);
    }

我的声音播放功能:

//plays a sound file
private void playSound(int sFile) {
    //set up MediaPlayer   
    final int medFile = sFile;

    Thread thread = new Thread(new Runnable() {
        public void run() {
            playSound = MediaPlayer.create(getApplicationContext(), medFile);
            playSound.start();
        }
    });
    thread.start();
}

我知道我可以使用如下方法:

mp.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                performOnEnd();
            }

            });

所以我可以这样:

    playSound.setOnCompletionListener(new OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer playSound) {
                         imgSheep.setImageResource(R.drawable.originalimage);
                }
     });
4

1 回答 1

2

你的问题是你的线程。在 playSound 中,您正在启动一个创建媒体播放器并播放声音的新线程。但是,您在 onCreate 中设置了 onCompletionListener。那里有一个竞争条件 - 如果新线程没有调度并且没有运行并在您点击该行之前设置 mediaPlayer 变量,您将因 NullPointerError 而崩溃。

我建议只是丢失线程。MediaPlayer 已经在后台播放并且不会挂起 UI 线程。

于 2013-03-30T16:04:39.643 回答