声音在java中 - 玩游戏时声音冻结 [英] Sound in java - Game freezes when playing sound

查看:112
本文介绍了声音在java中 - 玩游戏时声音冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以往我在游戏中播放声音,线程冻结,然后继续声音播放完毕之后。 code声音引擎:

When ever i play a sound in my game, the thread freezes, then continues after the sound has finished playing. Code for 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.

推荐答案

您可以启动一个线程来处理数据流的读取和写入。下面一起来看看:
我如何在Java中播放声音?

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?

举例code:

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

这篇关于声音在java中 - 玩游戏时声音冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆