当我删除System.out.println时,while循环似乎不起作用

时间:2018-04-18 03:22:45

标签: java if-statement while-loop audioinputstream

所以这个while循环几乎什么都不做,直到我改变bgmPlaying的值。它工作正常。但是,如果我删除了//上面测试的部分(没有任何换行符),它就不起作用。

这段代码实际上会检查音乐是打开还是关闭。

当我删除System.out.println()部分???

时,知道它为什么停止工作

这是我的代码:

import java.io.File;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;

/**
 * This class simply plays a background music in a seperate thread
 * @author Mohammad Nafis
 * @version 1.0
 * @since 04-03-2018
 *
 */
public class AudioPlayer implements Runnable{

    /**
     * this boolean indicates whether the background music is playing
     */
    private boolean bgmPlaying = true; 

    public void stopBGM() {
        bgmPlaying = false;
    }

    public void playBGM() {
        bgmPlaying = true;
    }

    /**
     * this is an overridden method from Runnable interface that executes when a thread starts
     */
    @Override
    public void run() {

        try {
            File soundFile = new File("sounds/epic_battle_music.wav");
            AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile);
            AudioFormat format = ais.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);
            Clip clip = (Clip)AudioSystem.getLine(info);
            clip.open(ais);
            clip.loop(Clip.LOOP_CONTINUOUSLY);

            //controlling the volume
            FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
            gainControl.setValue(-20);
                clip.start();




                while(true) {

                    if(bgmPlaying) {
                        gainControl.setValue(-20);
                    } else {
                        gainControl.setValue(-80);
                    }

                    while(bgmPlaying) {

                        //testing
                        System.out.println("BGM is on: ");


                        if(bgmPlaying == false) {
                            gainControl.setValue(-80);


                            break;
                        }
                    }

                    while(!bgmPlaying) {

                        //testing
                        System.out.println("BGM is off: ");

                        if(bgmPlaying == true) {
                            gainControl.setValue(-20);


                            break;
                        }
                    }
                }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

此代码位于我的Controller类中,用于调用停止和播放方法。

//adding action listener
    window.getpausebutton().addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ev) {   
            new Thread(new SoundEffect("sounds/clickSound.wav")).start();
            bgm.stopBGM();
        }
    });
    window.getplaybutton().addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ev) {
            new Thread(new SoundEffect("sounds/clickSound.wav")).start();
            bgm.playBGM();
        }
    });

1 个答案:

答案 0 :(得分:1)

使用volatileThread.sleep确实是解决问题的方法,尽管它应该可行。但更大的问题是代码忙 - 等待变量的状态改变,并取决于两个线程之间的共享状态。使用volatilesynchronized您可以管理这些问题,但有更好的方法。

java.util.concurrent包中有用于处理并发的电源工具。与之相比,线程,易失性,休眠(以及等待和通知)就像原始的手工工具。其中一个强大的工具是BlockingQueue及其各种实现,它们可以让你在Java中实现类似Actor Model的东西。

在Actor模型中,actor会相互发送消息以进行操作,但它们永远不会共享内存。您可以定义一些简单的消息,如PLAY,MUTE和STOP,并将这些消息从您的控制线程发送到您的播放器线程。如果您使用BlockingQueue,播放器看到消息就没有问题,并且它不必忙 - 等待消息到达。它可以简单地尝试take来自队列的消息,如果没有消息等待,它将一直阻塞,直到消息可用。

以下是您在代码中实现的方法:

public enum Command {
    PLAY, STOP, MUTE;
}

import java.io.File;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;

import java.util.Objects;
import java.util.Scanner;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * This class simply plays a background music in a separate thread
 *
 * @author Mohammad Nafis
 * @version 1.0
 * @since 04-03-2018
 */
public class AudioPlayer implements Runnable {
    private final String filename;
    private final BlockingQueue<Command> commandQueue =
            new LinkedBlockingQueue<>();

    public final static int LOUD = -20;
    public final static int QUIET = -80;

    public AudioPlayer(String filename) {
        this.filename = Objects.requireNonNull(filename);
    }

    public void perform(Command command) throws InterruptedException {
        commandQueue.put(Objects.requireNonNull(command));
    }

    @Override
    public void run() {
        try {
            File soundFile = new File(filename);
            AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile);
            AudioFormat format = ais.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);
            Clip clip = (Clip)AudioSystem.getLine(info);
            clip.open(ais);
            clip.loop(Clip.LOOP_CONTINUOUSLY);

            //controlling the volume
            FloatControl gainControl = (FloatControl)
                    clip.getControl(FloatControl.Type.MASTER_GAIN);
            gainControl.setValue(LOUD);
            clip.start();

            forever: while (true) {
                switch (commandQueue.take()) {
                    case PLAY:
                        gainControl.setValue(LOUD);
                        break;
                    case MUTE:
                        gainControl.setValue(QUIET);
                        break;
                    case STOP:
                        break forever;
                }
            }

            clip.stop();
            clip.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        AudioPlayer player = new AudioPlayer(args[0]);
        Thread thread = new Thread(player);
        thread.start();

        Scanner in = new Scanner(System.in);
        String cmd = "";
        System.out.println("Type mute or play. Or stop to exit.");
        do {
            System.out.print(": ");
            System.out.flush();
            cmd = in.nextLine();
            if ("play".equals(cmd)) player.perform(Command.PLAY);
            else if ("mute".equals(cmd)) player.perform(Command.MUTE);
            else if ("stop".equals(cmd)) player.perform(Command.STOP);
            else System.out.println("I didn't understand that, sorry.");
        } while (!"stop".equals(cmd));

        player.perform(Command.STOP);
        thread.join();
        System.out.println("Be seeing you.");
    }
}

一些注意事项:

  • 我在播放器停止后添加了对clip.stop()clip.close()的调用,以便音频系统不会保持后台线程运行,从而阻止程序退出。
  • perform(Command)方法虽然位于AudioPlayer类中,但会在调用它的控件线程上执行,但这没关系。因为队列是为并发而设计的,所以在控制线程上排队的命令将立即在播放器线程上可见。无需Thread.sleep
  • 我为两个不同的增益级别添加了常量。
  • 我将音频文件的名称作为命令行参数,因为我没有史诗般的战斗音乐。
  • 如果您尝试传入AudioPlayerperform构造函数和null方法都会抛出。