Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java MediaPlayer在循环中的应用_Java_Android - Fatal编程技术网

Java MediaPlayer在循环中的应用

Java MediaPlayer在循环中的应用,java,android,Java,Android,问题: 我的代码有问题。我想循环我的MediaPlayer,但当我使用while循环时,MediaPlayer正在播放,但应用程序被冻结。我知道,mediaplayer有setLooping方法,但我必须使用while循环,因为我需要更改代码中的声音 有人知道它的解决方案吗?谢谢 代码: public void play() { while(true) { if (player == null) { player =

问题: 我的代码有问题。我想循环我的MediaPlayer,但当我使用while循环时,MediaPlayer正在播放,但应用程序被冻结。我知道,mediaplayer有
setLooping
方法,但我必须使用while循环,因为我需要更改代码中的声音

有人知道它的解决方案吗?谢谢

代码:

    public void play() {
        while(true) {
            if (player == null) {
                player = MediaPlayer.create(context, R.raw.zvuk);
                player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        stopPlayer();
                    }
                });
            }
            player.start();
        }
    }

    public void stopPlayer() {
        if (player != null) {
                player.release();
                player = null;
        }
    }
}

您使用的是无限循环,它永远不会结束。将代码替换为以下内容:

public void play() {
            if (player == null) {
                player = MediaPlayer.create(context, R.raw.zvuk);
                player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        // play again or write your logic for repeat 
                        play();
                    }
                });
            }
            player.start();
       
    }

    public void stopPlayer() {
        if (player != null) {
                player.release();
                player = null;
        }
    }