简体   繁体   English

Java声音-播放声音时游戏冻结

[英]Sound in java - Game freezes when playing sound

Whenever I play a sound in my game, the thread freezes then continues after the sound has finished playing. 每当我在游戏中播放声音时,线程就会冻结,然后在声音播放完毕后继续。 Code for the sound engine: 声音引擎的代码:

package com.kgt.platformer;

import java.io.File;
import java.io.IOException;    
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class Sound {
    private final static int BUFFER_SIZE = 12800000;
    private static File soundFile;
    private static AudioInputStream audioStream;
    private static AudioFormat audioFormat;
    private static  SourceDataLine sourceLine;

    /**
     * 
     * @param filename the name of the file that is going to be played
     *
     */
    public static void playSound(String filename){

        String strFilename = filename;

        try {
            soundFile = new File(strFilename);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }

        try {
            audioStream = AudioSystem.getAudioInputStream(soundFile);
        } catch (Exception e){
            e.printStackTrace();
           System.exit(1);
        }

        audioFormat = audioStream.getFormat();

        DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
        try {
            sourceLine = (SourceDataLine) AudioSystem.getLine(info);
            sourceLine.open(audioFormat);
        } catch (LineUnavailableException e) {
            e.printStackTrace();
            System.exit(1);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }


        sourceLine.start();

        int nBytesRead = 0;
        byte[] abData = new byte[BUFFER_SIZE];
        while (nBytesRead != -1) {
            try {
                nBytesRead = audioStream.read(abData, 0, abData.length);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (nBytesRead >= 0) {
                @SuppressWarnings("unused")
                int nBytesWritten = sourceLine.write(abData, 0, nBytesRead);
            }
        }

        sourceLine.drain();
        sourceLine.close();
    }
}

What ends up happening is I start the game, it plays sound, the games freezes then continues. 最终发生的事情是我开始游戏,播放声音,游戏冻结然后继续。

You could start a thread to handle the reading and writing of the streams. 您可以启动一个线程来处理流的读取和写入。 Take a look here: How can I play sound in Java? 在这里看看: 如何用Java播放声音?

Example code: 示例代码:

new Thread(new Runnable() {
  public void run() {
    Sound.playSound("Test.wav");
  }
}.start();

A Java Sound based Clip uses it's own (daemon) Thread . 基于Java声音的Clip使用它自己的(守护程序) Thread See this example which will loop 2 clips at one (though be warned, turn the volume down). 请参见此示例,该示例将使2个剪辑一次循环(尽管警告,请调低音量)。 Note also the 2nd clip takes a few moments to load. 请注意,第二个片段需要一些时间才能加载。 Wait till you see the JOptionPane - then both clips should be looping. 等待直到看到JOptionPane然后两个剪辑都应该循环播放。

import java.net.URL;
import javax.swing.*;
import javax.sound.sampled.*;

public class LoopSounds {

    public static void main(String[] args) throws Exception {
        URL url1 = new URL(
            "http://pscode.org/media/leftright.wav");
        URL url2 = new URL("http://pscode.org/media/100_2817-linear.wav");
        Clip clip1 = AudioSystem.getClip();
        Clip clip2 = AudioSystem.getClip();
        // getAudioInputStream() also accepts a File or InputStream
        AudioInputStream ais1 = AudioSystem.
            getAudioInputStream( url1 );
        clip1.open(ais1);
        clip1.loop(Clip.LOOP_CONTINUOUSLY);

        AudioInputStream ais2 = AudioSystem.
            getAudioInputStream( url2 );
        clip2.open(ais2);
        clip2.loop(Clip.LOOP_CONTINUOUSLY);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // A GUI element to prevent the Clip's daemon Thread
                // from terminating at the end of the main()
                JOptionPane.showMessageDialog(null, "Close to exit!");
            }
        });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM