简体   繁体   中英

implementing sound into a java game

I've followed Buckys java game development with slick for the basic setup for the game and since then I've taken it into my own hands. Currently I'm just building the menu and its pretty much finished except i want to add sound to it. I've been stuck on this for a week so its not like i haven't done any research for this, i just can't make it work. Now I've found some code to do this which seems to make sense, how could i implement this or if you have a better idea for how to add some sound, appreciated.

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

static String soundtrack = "res/doxx.wav";

public void sound(String path){

    try{
        AudioInputStream audio = AudioSystem.getAudioInputStream(Menu.class.getResource(path));
        Clip clip = AudioSystem.getClip();
        clip.open(audio);
        clip.start();
    } catch (Exception e){
        System.out.println("check "+path+"\n");
        e.printStackTrace();
    }
}

edit: This code has been taken out of the program now, but feel free to post answers based on it

That's the code related to adding sound so far, here is the entirety of my menu class, its not to huge. To be honest you probably don't need to look at it in detail, its currently all based around graphics and two buttons (start and quit) which are spinning.

package javagame;

import org.lwjgl.input.Mouse;
import org.newdawn.slick.*;
import org.newdawn.slick.state.*;


public class Menu extends BasicGameState {

double pi=3.14159265359;
float beanPosY = 330;
float beanPosX = 70;
double gravity = 0.01;
double angleStart=1.5*pi;
double angleQuit=0.5*pi;
int radius=120;
int centerX=300;
int centerY=160;
float startPosX = (float) (centerX + Math.sin(angleStart)*radius);
float startPosY = (float) (centerY + Math.cos(angleStart)*radius);
float quitPosX = (float) (centerX + Math.sin(angleQuit)*radius);
float quitPosY = (float) (centerY + Math.cos(angleQuit)*radius);
double force = 0;
public Menu(int state){
}

public void init(GameContainer gc, StateBasedGame sbg) throws SlickException{
    Sound music = new Sound();
    music.playBackGround("res/doxx.wav");
}

public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException{     
    Image background = new Image("res/background640x480.fw.png");
    g.drawImage(background, 0, 0);

    Image start = new Image("res/Start100x100.fw.png");
    Image quit = new Image("res/quit100x100.fw.png");
    start.draw(startPosX,startPosY);
    quit.draw(quitPosX,quitPosY);

    Image grass = new Image("res/grass640x150.fw.png");
    g.drawImage(grass,0,340);

    Image bean = new Image("res/bean.jpg");
    bean.draw(beanPosX, beanPosY);
}

public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException{
    int posX = Mouse.getX();
    int posY = Mouse.getY();
    double constant=0.002*pi;

    startPosX = (float) (centerX + Math.sin(angleStart)*radius);
    startPosY = (float) (centerY + Math.cos(angleStart)*radius);
    quitPosX = (float) (centerX + Math.sin(angleQuit)*radius);
    quitPosY = (float) (centerY + Math.cos(angleQuit)*radius);

    angleStart+=constant;
    angleQuit+=constant;
    if (angleStart>=2*pi){
        angleStart-=2*pi;
    }
    if (angleQuit>=2*pi){
        angleQuit-=2*pi;
    }
    //button interactions
    menuInteraction(posX,posY,sbg);


    if (beanPosY>=330){
        force=1;
    }
    beanPosY-=force;
    force-=gravity;
}

public int getID(){
    return 0;
}

private void menuInteraction(int posX, int posY, StateBasedGame sbg){
    //play button
    float startXDist=posX-(startPosX+50);
    float startYDist=(480-posY)-(startPosY+50);
    float startDist=(float) Math.sqrt((startXDist*startXDist)+(startYDist*startYDist));
    if(startDist<=50){
        if(Mouse.isButtonDown(0)){
            sbg.enterState(1);
        }
    }

    //quit button
    float quitXDist=posX-(quitPosX+50);
    float quitYDist=(480-posY)-(quitPosY+50);
    float quitDist=(float) Math.sqrt((quitXDist*quitXDist)+(quitYDist*quitYDist));
    if(quitDist<=50){
        if(Mouse.isButtonDown(0)){
            System.exit(0);
        }
    }
}

}

edit: The code above now creates an object within the 'init()' method which calls upon the 'Sound' class and its method 'playBackGround()'. The code for the Sound class is given in the answer below from JavaNewb.

edit: The errors produced by this code are as follows:

java.lang.NullPointerException
at com.sun.media.sound.StandardMidiFileReader.getSequence(Unknown Source)
at javax.sound.midi.MidiSystem.getSequence(Unknown Source)
at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(Unknown Source)
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at javagame.Sound.run(Sound.java:45)
at java.lang.Thread.run(Unknown Source)

Final point, i have tried things such as the LWJGL libraries, i can't make sense of them. Also i realize how much I'm asking as I'm basically asking for someone to code this into my game which i wish i didn't have to do but i don't know how else to solve my problem without posting it on here.

PS. Its not like i haven't tried to do this myself, so don't be a pain and say I've made no effort

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;

public class Sound implements Runnable
{
    private boolean running = false;
    private Thread thread;

    public Sound()
    {
        this.start();
    }

    public void start()
    {
        if(running)
            return;
        this.thread = new Thread(this);
        this.running = true;
        this.thread.start();
    }

    //
    private boolean playSong = false;
    private AudioInputStream inputStream;
    private String url;
    private Clip clip;

    @Override
    public void run()
    {
        while(running)
        {
            if(inputStream == null && playSong)
            {
                this.playSong = false;
                try
                {
                    this.inputStream = AudioSystem.getAudioInputStream(Sound.class.getResource(url));
                    this.clip.open(inputStream);
                    this.clip.loop(10);
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    public void playBackGround(String string) // call to play .wav file
    {
        if(this.clip != null)
        {
            this.clip.stop();
            this.clip.close();
        }
        try
        {
            this.clip = AudioSystem.getClip();
        }
        catch(LineUnavailableException e)
        {
            e.printStackTrace();
        }
        url = string + ".wav";
        this.playSong = true;
        this.inputStream = null;
    }

    public void disposeSound()
    {
        if(this.clip != null)
        {
            this.clip.stop();
            this.clip.close();
        }
        this.clip = null;
        this.playSong = false;
        this.inputStream = null;
    }
}

This error occurs when you try to create an AudioInputStream from a null URL. Make sure that url is not null, make sure that you reference a correct file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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