簡體   English   中英

背景音樂線程在游戲結束時消失而不是暫停

[英]Background music thread dying at game over rather than pausing

我正在處理一個蛇克隆項目,並且在實現一個功能時遇到了麻煩,即背景音樂僅在我的游戲過屏期間停止。

我的音樂在第一輪游戲中播放,但在我按下游戲的重置鍵后不會再次啟動。 我已經調試到看到我創建的循環音樂的線程在游戲結束時消失了,我不知道如何解決這個問題。

SoundFX backgroundSongLoop = new SoundFX(backgroundSong, true);

public Gameplay() {
    addKeyListener(this);
    setFocusable(true);
    setFocusTraversalKeysEnabled(false);


    //the speed of the snake
    timer = new Timer(clockSpeed, this);
    
    backgroundSongLoop.start();
    timer.start();
}

public void paint(Graphics g){

    //region Snake-Snake Collision
    for (int b=1; b<lengthOfSnake; b++){
        if(snakeXLength[b]==snakeXLength[0] && snakeYLength[b]==snakeYLength[0]){
            backgroundSongLoop.setOn(false);
            failedSoundFX.playSound(failSound);
            failed=true;
            timer.stop(); }

//region restart function
    if (failed){
        if (e.getKeyCode()==KeyEvent.VK_SPACE) {
            backgroundSongLoop.setOn(true);
            score = 0;
            lengthOfSnake = 3;
            moves = 0;
            repaint();
            timer.start();
        }
    }
    //endregion




public class SoundFX extends Thread{

private final String soundName;
public boolean isOn;

public SoundFX(String soundName) {
    this.soundName = soundName;
}
public SoundFX(String soundName, boolean isOn) {
    this.soundName = soundName;
    this.isOn = isOn;
}

public void setOn(boolean on) {
    isOn = on;
}

public void playSound(String soundName){
    File soundFile = new File(soundName);
    try{
        Clip clip = AudioSystem.getClip();
        clip.open(AudioSystem.getAudioInputStream(soundFile));
        clip.start();
    } catch (Exception e){
        e.printStackTrace();
    }
}

@Override
public void run() {
    //public void loopSong(String soundName, boolean playing){
        File soundFile = new File(soundName);
        try{
            Clip clip = AudioSystem.getClip();
            clip.open(AudioSystem.getAudioInputStream(soundFile));
                while (isOn){
                    clip.loop(Clip.LOOP_CONTINUOUSLY);
                }
                while (!isOn){
                    clip.stop();
                }
        } catch (Exception e){
            e.printStackTrace();
        }
}

}

兩件事情:

  1. 使用clip.setFramePosition(0)定位剪輯以clip.setFramePosition(0)開始重新啟動。

  2. clip.open()方法放在構造函數中並使clip成為實例變量。 這樣,當您希望重新啟動它時,只需要以下內容:

     public void play() { clip.setFramePosition(0); clip.loop(); }

通過這樣做,您可以避免每次希望播放提示時從文件位置重新加載。 直到所有文件操作都完成后,cue 才會開始,因此這種方法可以讓您更快地開始。

我認為如果你這樣做,你也可以編寫一個調用clip.stop()的方法,然后直接在你的SoundFX類上調用所有這些方法,而無需擴展Thread

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM