No sound in java games

Sound issues in jar file

I have a very weird issue I cant fix. I’m currently making a game and I want sound in the game. It is supposed to be run as a jar file and the game works perfectly fine when running it from eclipse. The SoundPlayer is part of an external jar library that I use in the game. It then takes a name, a folder and plays the sound. The sound is located in a sub-folder of the folder where the FTSound object class is. I’ve checked the jar, and the sound files are included and they are in the same place as in eclipse. Now to the weird issue I’ve come across: When I run the jar file by double-clicking it, everything works except the sound. It is completely missing. However, if I start the jar via cmd, the sound works fine. It is the exact same jar. Any ideas? I’d much appreciate your help! The sound is played with the following code:

public static void playSound(final FTSound sound) < new Thread(new Runnable() < @Override public void run() < try< Clip clip = AudioSystem.getClip(); AudioInputStream inputStream = AudioSystem.getAudioInputStream(sound.getClass().getResource(sound.getFolderName() + "/" + sound.getSoundName())); clip.open(inputStream); clip.start(); >catch (Exception e) < e.printStackTrace(); >> >).start(); > 

1 Answer 1

A few ideas come to mind. You said you’re using eclipse. When you extract your files to the .jar, be sure that your audio files are all extracted to the same place. If you are clicking on the .jar outside of the directory which contains your sound files and it’s not a shortcut, but your run inside the same directory in the cmd, this could cause the issue you have described. Although it doesn’t really fix the issue, a workaround I would suggest is writing a bat to start your game at the command prompt. this will give you a clickable file which also plays the sound. I don’t see any issues in your code, and if you have gotten the sound to play, then there probably aren’t any. One other thing: the clip object can’t run sound well for more than a few seconds. If you’re looking for a sound effect, it’s great, but otherwise, you should try using this method:

new Thread(new Runnable() < SourceDataLine soundLine; public void run() < soundLine = null; int BUFFER_SIZE = 64*1024; // 64 KB // Set up an audio input stream piped from the sound file. try < AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(this.getClass().getResource("title.wav")); AudioFormat audioFormat = audioInputStream.getFormat(); DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); soundLine = (SourceDataLine) AudioSystem.getLine(info); soundLine.open(audioFormat); soundLine.start(); int nBytesRead = 0; byte[] sampledData = new byte[BUFFER_SIZE]; while (nBytesRead != -1) < nBytesRead = audioInputStream.read(sampledData, 0, sampledData.length); if (nBytesRead >= 0) < // Writes audio data to the mixer via this source data line. soundLine.write(sampledData, 0, nBytesRead); >> > catch (Exception ex) < ex.printStackTrace(); >finally < soundLine.drain(); soundLine.close(); >> >).start(); 

Thanks for your answer! I’m not sure how I’m going to fix this though. I experimented for a while trying your solution as well and now i get sound when i double-click the jar. The problem now is that the sound is working for a while, and then all of a sudden it wipes out all sound on the computer, such that I need to reboot it. I think my sound card might be the cause, I am not sure though.

Yeah, that sounds like an issue specific to your computer. This method is funny sometimes, though. On my friend’s computer, it turns his sound on if it’s off; he has an alienware. On my Toshiba, however, it works perfectly fine. I have no idea why, though.

Читайте также:  Javascript this file path

Источник

How to play sounds in Java games?

(Players are a list of clips that I open at the start with the aim to reduce latency, a line listener closes the line when the stop event is retrieved.) The problem I’m facing is intermittent delays of upto 1 second when playing a sound. This is pretty poor. Is there any way to improve this? Are SourceDataLines worth considering?

2 Answers 2

The Java Applet is streaming your clip whenever you want to play it, which is why you are getting a delay as the sound file hasn’t been loaded into memory yet.

It’s been awhile since I have done Java applet programming, but I do remember that I used to pre-load all my clips and then subsequent calls to play would not re-open the files.

Here is some code from one of my old projects

Clip shoot; private loadShootWav() < AudioInputStream sample; sample = AudioSystem.getAudioInputStream(this.getClass().getResource("shoot.wav")); shoot = AudioSystem.getClip(); shoot.open(sample); >public void playShootSFX()

Hi — thanks for your answer. The same sound could be required to be played multiple times. Would you suggest some sort of pooling of multiple clips for each sound effect before hand?

Yeah — I usually implement a ‘SoundManager’ singleton class that loads all the clips. The above code will play the sound multiple times, but reset the clip each time. If you want to say play 5 of the same sound, but mix it at slightly different intervals I’d suggest trying you load 5 clips and then when you call playSFX() increment a counter that points at whichever is the next clip to be played.

@JSmyth I’m doing something just like this, but if I open multiple AudioInputStream of the same sound file, I start getting LineUnavailableException. Can you take a look at my question? stackoverflow.com/questions/20184650/…

If I am reading your code correctly, you are finding an unopened clip and opening it before playing it. It would be quicker to take opened clips and restart them. You might have to stop and reset their positions first, as shown by JSmyth in playShootSFX() example.

I am getting pretty good response with SourceDataLines. The nice thing is that they start quicker than an unopened Clip, since they start right away instead of waiting until ALL the data for the sound is loaded into RAM (which occurs each time you «open» a Clip).

But, yes, if you have a lot of little sounds that are played frequently, a clip pool is the way to go. If you want them to overlap, or always play to completion, then you need multiple copies. If not, then stop, reset to 0 and restart. But don’t keep reopening! If you are doing that, you might as well use a SourceDataLine.

Источник

Playing music in a Java game

I’m trying to have some background music in a game I’m programming in Java. I have the coded, got no errors whatsoever. The only problem is that no music plays. Here’s what I programmed:

import sun.audio.AudioData; import sun.audio.AudioPlayer; import sun.audio.AudioStream; import sun.audio.ContinuousAudioDataStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; public void startBGMusic() try< InputStream in = new FileInputStream(new File("opening1.mid")); AudioStream audioStream = new AudioStream(in); AudioPlayer.player.start(audioStream); >catch(Exception error)

3 Answers 3

import sun.audio.*; import java.io.*; public class AudioTest < private static AudioStream theStream; // Main method public static void main(String[] args)< try< theStream = new AudioStream(new FileInputStream("opening1.mid")); AudioPlayer.player.start(theStream); >catch(Exception e) >//end main >//end AudioTest class 

I would like to strongly recommend using the javax.sound.sampled library for game audio. As far as I know these old sun.audio libraries are obsolete or deprecated or something. I don’t use them at all, so I can’t comment on how to work with them or whether code that works one one system will work on another. I don’t think you can safely assume that it will.

Читайте также:  Yii php mysql docker

The Java Tutorials Trail: Sound has what you need, although the tutorial is admittedly a difficult read.

The section on playing back sound will be the main point of focus.

Some folks make use of libraries, such as TinySound (available for free, on github), as a way to simplify game sf/x programming. You can find out more about it and other sf/x libraries on the java game programming site java-gaming.org/

I find myself wondering why so many people end up trying to use these old sun libraries. Maybe it’s just a side effect: the ones that do inevitably end up having problems and come asking questions on StackOverflow. As a result, that population of is «over-represented»?

Источник

Java game sound effects isn’t working correctly

I’m trying to do my school project (a simple Java game) and I cant’s get the sound effects work. I’m doing it using Clip and now my playSound-method looks like this:

public void playSound(File filename) < try < AudioInputStream sound = AudioSystem.getAudioInputStream(filename); Clip clip = AudioSystem.getClip(); clip.open(sound); clip.setFramePosition(0); clip.start(); >catch (UnsupportedAudioFileException ex) < ex.printStackTrace(); >catch (IOException ex) < ex.printStackTrace(); >catch (LineUnavailableException ex) < ex.printStackTrace(); >> 

I have different sound effects as attributes (Files) and I call that method when I want to play some sound. Everything works fine: the sound plays for example when the player eats something but sometimes the sounds go grazy. The eating sound is being played while the player isn’t eating anything. Do you know what’s wrong? Is it problematic to play several sound effects like this? Thanks! 🙂

1 Answer 1

The following advice may or may not help with your situation.

You are loading Clips from disk every time you play a sound. Clips were designed to be loaded once, and called on an as-needed basis. To replay a clip, you reset it back to the 0th millisecond or frame and then call play as you do here. This way, it starts very quickly. The way you have programmed it, the clip will not even start playing until it has fully loaded from disk into memory, and the setFramePosition(0) is superfluous since a newly created Clip will always play from the start (unless you’ve explicitly set it to some other frame position).

So, I recommend at the start of the game, loading the clips once into objects that will persist, and reference them on an as-needed basis, at which time you only need to call the setFramePosition(0) and the play() methods.

If the sounds are playing at odd times, I’d take a harder look at the logic that calls the sounds. While your method is not optimal, it does work, and would only result in oddly late play times if the loading of the sound file were delayed for some reason or another. But if your sounds are more than a few seconds long, those loading delays could be the source of the problem.

One other thought, a SourceDataLine will start playing more quickly than creating, loading and playing a new Clip. It takes a bit more cpu to play an SDL than a Clip, but it is still a reasonable way to go if the sound files are on the long side.

Источник

Java sound not playing on executable jar

I’m making a game, and upon exporting the game to a .jar file, I stumbled upon a problem: I can’t make the sound play. I have made lot of research about this, and I’m starting to think this is some problem with JAVA. I also realized that I’m not the only one with this problem, but there was no answer provided to those people that could help me. I studied the difference between getClass() and getClassLoader(), and tryed both cases, but still nothing. But The problem is not about loading the resources anyway, it is about the sound not playing, even though it loads. The game plays nicely, loading all the sprites, but nothing of sound. During my research about this, I learned the I could execute the game using «java -jar file.jar» on command, and the sound started to work. However this doesn’t sound like a good option for me, since I have the intention of distributing the game. Here is a test I made, that shows exactly what I’m talking about. You can add any image and sound, and test it by your selves.

package testando; import java.awt.BorderLayout; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; 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.LineEvent; import javax.sound.sampled.LineListener; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; public class Testando extends JFrame < private final LineListener myLineListener; public Testando() < super(); setLayout( new BorderLayout() ); setBounds( 200, 200, 500, 500 ); myLineListener = new MyLineListener(); MultiSound multiSoundPanel = new MultiSound(); addWindowListener( new WindowAdapter() < @Override public void windowClosing( WindowEvent e ) < System.exit( 0 ); >>); add( multiSoundPanel ); > private class MultiSound extends JPanel < final BufferedImage desertImage; MultiSound()< super( null, true ); final AudioInfo audioInfos = new AudioInfo( "testando/Iron_Click.wav" ); addMouseListener( new MouseListener() < final AudioInfo audioInfo = audioInfos; @Override public void mousePressed( MouseEvent e ) < Sound sound = new Sound( audioInfo ); new Thread(sound).start(); >@Override public void mouseClicked( MouseEvent e ) <> @Override public void mouseReleased( MouseEvent e ) <> @Override public void mouseEntered( MouseEvent e ) <> @Override public void mouseExited( MouseEvent e ) <> >); java.net.URL streamURL = Thread.currentThread().getContextClassLoader().getResource( "testando/Desert.jpg" ); BufferedImage desertImagebuff = null; try < desertImagebuff = ImageIO.read( streamURL ); >catch ( IOException ex ) < StringBuilder sb = new StringBuilder(ex.toString()); for (StackTraceElement ste : ex.getStackTrace()) < sb.append("\n\tat "); sb.append(ste); >String trace = sb.toString(); JOptionPane.showMessageDialog( null, trace, "ERROR", JOptionPane.INFORMATION_MESSAGE); System.exit( -1 ); > desertImage = desertImagebuff; > @Override protected void paintComponent( Graphics g ) < super.paintComponent( g ); //To change body of generated methods, choose Tools | Templates. Graphics2D g2 = (Graphics2D)g.create(); Rectangle rect = getVisibleRect(); double desSx = ((rect.width*1.0d)/desertImage.getWidth()); double desSy = ((rect.height*1.0d)/desertImage.getHeight()); //To keep the image scalled to the panel; AffineTransform scale = AffineTransform.getScaleInstance( desSx, desSy ); AffineTransformOp transformer = new AffineTransformOp( scale, null ); g2.drawImage( desertImage, transformer , rect.x, rect.y ); g2.dispose(); >> private class AudioInfo < final AudioFormat audioFormat; final int size; final byte[] audio; final DataLine.Info info; AudioInfo( String path )< java.net.URL streamURL = Thread.currentThread().getContextClassLoader().getResource( path ); AudioFormat toAudioFormat = null; int toSize = -1; byte[] toByte = null; DataLine.Info toInfo = null; try < InputStream stream = new BufferedInputStream( streamURL.openStream() ); AudioInputStream audioInputStream = AudioSystem.getAudioInputStream( stream ); toAudioFormat = audioInputStream.getFormat(); toSize = (int) ( toAudioFormat.getFrameSize() * audioInputStream.getFrameLength() ); toByte = new byte[toSize]; toInfo = new DataLine.Info(Clip.class, toAudioFormat, toSize); audioInputStream.read(toByte, 0, toSize); >catch ( UnsupportedAudioFileException | IOException ex ) < StringBuilder sb = new StringBuilder(ex.toString()); for (StackTraceElement ste : ex.getStackTrace()) < sb.append("\n\tat "); sb.append(ste); >String trace = sb.toString(); JOptionPane.showMessageDialog( null, trace, "ERROR", JOptionPane.INFORMATION_MESSAGE); System.exit( -1 ); > audioFormat = toAudioFormat; size = toSize; audio = toByte; info = toInfo; > > private class MyLineListener implements LineListener < @Override public void update( LineEvent event ) < if ( event.getType( ) == LineEvent.Type.STOP ) event.getLine().close(); >> private class Sound implements Runnable < private final Clip sound; Sound( AudioInfo audioInfo )< AudioFormat audioFormat = audioInfo.audioFormat; int size = audioInfo.size; byte[] audio = audioInfo.audio; DataLine.Info info = audioInfo.info; Clip clip = null; try < clip = (Clip) AudioSystem.getLine( info ); clip.open( audioFormat, audio, 0, size ); clip.addLineListener( myLineListener ); >catch ( LineUnavailableException ex ) < clip = null; >sound = clip; > @Override public void run() < sound.start(); >> public static void main( String[] args ) < Testando testando = new Testando(); testando.setVisible( true ); >> 

Источник

Оцените статью