Buzzing on Exit - java

I'm trying to build a game that uses sound effects. I haven't dealt with the Java API before so I may be making some mistakes. That said though, the effects work great — my only problem is that I get a strange buzzing sound for maybe a second whenever my program exits.
Any idea how I might get rid of it? Right now I'm trying to kill any playing sounds just before the exit takes place with the killLoop() method, but that isn't getting me anywhere.
I'd appreciate your help!
public class Sound
{
private AudioInputStream audio;
private Clip clip;
public Sound(String location)
{
try {
audio = AudioSystem.getAudioInputStream(new File(location));
clip = AudioSystem.getClip();
clip.open(audio);
}
catch(UnsupportedAudioFileException uae) {
System.out.println(uae);
}
catch(IOException ioe) {
System.out.println(ioe);
}
catch(LineUnavailableException lua) {
System.out.println(lua);
}
}
public void play()
{
clip.setFramePosition(0);
clip.start();
}
public void loop()
{
clip.loop(clip.LOOP_CONTINUOUSLY);
}
public void killLoop()
{
clip.stop();
clip.close();
}
}
public class Athenaeum
{
public static void main(String[] args) throws IOException
{
final Game game = new Game();
GUI athenaeumGui = new GUI(game);
athenaeumGui.setSize(GUI.FRAME_WIDTH, GUI.FRAME_HEIGHT);
athenaeumGui.setTitle("Athenaeum");
athenaeumGui.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
athenaeumGui.setLocationRelativeTo(null);
athenaeumGui.setMinimumSize(new Dimension(GUI.FRAME_WIDTH, GUI.FRAME_HEIGHT));
athenaeumGui.buildGui();
athenaeumGui.setVisible(true);
athenaeumGui.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we)
{
game.killAudio(); // method calls Sound.killLoop()
System.exit(0);
}
});
}
}

In Java api, they say that the AudioInputStream class has a ".close()" method that "Closes this audio input stream and releases any system resources associated with the stream". Maybe this is something you can try.

Related

Resource is not grabbed when exporting to .JAR

I'm trying to get a better understanding of Java by creating a small 2D game. I feel like the best way to learning is by struggling, so I try not to get help on any problems I have; I just solve them myself. However, I've tried almost everything any I can't get my background music to play in my exported version of my game. All the images work and everything else pulled using the " getClass()" method works, but the music doesn't.
Sorry I have to put all of the code from my BackgroundMusicManager class, but because I want to do things without help, my first version of my programs are usually very messy and require a lot of optimization. In short, you kinda have to see where things are called and initialized and whatnot to really see how the things work.
package com.cs.dd.audioManager;
import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import javax.sound.sampled.*;
import com.nickgirga.dd.main.*;
import sun.applet.Main;
public class BackgroundMusicManager implements Runnable {
//URLs
public URL mmBgMusicURL = getClass().getResource("/audio/backgroundMusic/casual.wav");
//Files
public File[] bgMusics = { new File(mmBgMusicURL.getFile()) };
public File bgMusic = bgMusics[0];
private static Clip clip;
public static int newGameState;
public static boolean enabled = true;
public static boolean asPlaying = false;
public static Thread bgMusicPlayer = new Thread(new BackgroundMusicManager());
public void play () {
if (enabled) {
try {
if (bgMusic != null) clip = AudioSystem.getClip();
if (bgMusic != null) clip.open(AudioSystem.getAudioInputStream(bgMusic));
if (bgMusic != null) clip.start();
//System.out.println(bgMusics[0].getAbsolutePath());
loopChecker();
bgMusicPlayer.wait();
} catch (LineUnavailableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (Exception e) {
//e.printStackTrace();
}
}
}
public void loopChecker () {
while (true) {
if (clip.getMicrosecondPosition() >= clip.getMicrosecondLength()) {
bgMusicPlayer.notify();
}
if (!(GameState.state == newGameState)) {
setClip();
}
}
}
public void setClip () {
//System.out.println("setClip");
newGameState = GameState.state;
if (GameState.state == 0) {
clip.stop();
bgMusic = bgMusics[0];
bgMusicPlayer.notify();
} else {
if (GameState.state == 1) {
clip.stop();
bgMusic = bgMusics[0];
bgMusicPlayer.notify();
} else {
clip.stop();
bgMusic = null;
bgMusicPlayer.notify();
}
}
}
#Override
public void run() {
while (true) {
play();
}
}
}
After exporting this as a JAR with the libraries packed into it, the console reads:
java.io.FileNotFoundException: audio\backgroundMusic\casual.wav (The system cannot find the path specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at com.sun.media.sound.WaveFloatFileReader.getAudioInputStream(Unknown Source)
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at com.cs.dd.audioManager.BackgroundMusicManager.play(BackgroundMusicManager.java:33)
at com.cs.dd.audioManager.BackgroundMusicManager.run(BackgroundMusicManager.java:89)
at java.lang.Thread.run(Unknown Source)
I extracted the JAR and found the file exactly where the FileNotFoundException points, so I'm left very confused. The audio works while running in Eclipse. The images still show in the export. Why will it work with the images, but not the audio?
Any help is very appreciated! Thank you!!!
Instead of
getClass().getResource("/audio/backgroundMusic/casual.wav");
use
getClass().getClassLoader().getResourceAsStream("/audio/backgroundMusic/casual.wav")
In this way it will look from the root, not from the path of the current invoking class

JAVA - Sounds not playing after jar exported

I have the problem that after i export my java project no sound is playing.
I searched in the internet and i found that:
Main.class.getResourceAsStream("fileloc");solves that problem
But my class uses this..
Where is the problem?
public class Sounds {
private static Clip eat;
public static Clip collect;
private static Clip lsd;
private static AudioInputStream inputStream;
private static FloatControl gainControl;
public static void getSounds(){
try{
eat = getClip("/sound/collect/eat.wav");
collect = getClip("/sound/collect/collect.wav");
lsd = getClip("/sound/LSD.wav");
} catch(LineUnavailableException | UnsupportedAudioFileException| IOException e){
e.printStackTrace();
}
}
private static Clip getClip(String loc) throws LineUnavailableException, UnsupportedAudioFileException, IOException{
Clip c = AudioSystem.getClip();
inputStream = AudioSystem.getAudioInputStream(Spielfeld.class.getResourceAsStream(loc));
c.open(inputStream);
gainControl = (FloatControl) c.getControl(FloatControl.Type.MASTER_GAIN);
gainControl.setValue(+6.0f);
c.setMicrosecondPosition(0);
return c;
}
public static void playSound(final String url) {
switch(url){
case "collect/collect.wav": collect.start(); collect.setMicrosecondPosition(0); break;
case "collect/eat.wav": eat.start(); eat.setMicrosecondPosition(0); break;
case "LSD.wav": lsd.start(); lsd.setMicrosecondPosition(0); break;
}
}
}
Thank you for your help
No sound after export to jar
Thank you trinityalps ;) (https://stackoverflow.com/users/5012832/trinityalps)

Sound problems in Java

I have some questions about playing sound in Java and I hope you can help me out.
1. How can I stop a playing sound with a "Stop" button?
2. How can I slow down (or cooldown time) a sound?
3. I want to create a option frame where I can adjust volume and have mute option, how can I do that?
This is my code:
private void BGM() {
try {
File file = new File(AppPath + "\\src\\BGM.wav");
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(file));
clip.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
Any help will be greatly appreciated, and, Have a nice day!
You're working in an Object Oriented programming lanuage, so let's take advantage of that and encapsulate the management of the clip/audio into a simple class...
public class AudioPlayer {
private Clip clip;
public AudioPlayer(URL url) throws IOException, LineUnavailableException, UnsupportedAudioFileException {
clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(url.openStream()));
}
public boolean isPlaying() {
return clip != null && clip.isRunning();
}
public void play() {
if (clip != null && !clip.isRunning()) {
clip.start();
}
}
public void stop() {
if (clip != null && clip.isRunning()) {
clip.stop();
}
}
public void dispose() {
try {
clip.close();
} finally {
clip = null;
}
}
}
Now, to use it, you need to create a class instance field which will allow you to access the value from anywhere within the class you want to use it...
private AudioPlayer bgmPlayer;
Then, when you need it, you create an instance of AudioPlayer and assign it to this variable
try {
bgmPlayer = new AudioPlayer(getClass().getResource("/BGM.wav"));
} catch (IOException | LineUnavailableException | UnsupportedAudioFileException ex) {
ex.printStackTrace();
}
Now, when you need to, you simply call bgmPlayer.play() or bgmPlayer.stop()

AudioClip is not working, and it should

I have been trying to play a sound in java and I am stuck.
public class Audioapp extends JApplet
{
public class Sound{
public AudioClip song;
public URL songPath;
Sound(){
try{
songPath = new URL(getCodeBase(), "leftfordeath.wav");
song = Applet.newAudioClip(songPath);
}
catch (Exception e) {}
}
public void playSoundOnce(){
song.play();
}
}
public void init(){
Sound test = new Sound();
test.playSoundOnce();
}
}
When I call init from my main, it says there is a nullPointerExeption on song.play();
what am I doing wrong, please help...
try substituting this code where you have the playsoundOnce code and see how you get on.
public void playSoundOnce()
{
try
{
InputStream inputStream = getClass().getResourceAsStream(leftfordeath.wav);
AudioStream audioStream = new AudioStream(inputStream);
AudioPlayer.player.start(audioStream);
}
catch (Exception e)
{
if (debugFileWriter!=null) e.printStackTrace(debugFileWriter);
}
}

Clip not playing any sound

Well, the title says all, I tried playing a wav file using javax.sound and nothing is happening. I have tried many different files without any luck.
public static void main(String[] args) throws IOException, UnsupportedAudioFileException, LineUnavailableException
{
File in = new File("C:\\Users\\Sandra\\Desktop\\music\\rags.wav");
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(in);
Clip play = AudioSystem.getClip();
play.open(audioInputStream);
FloatControl volume= (FloatControl) play.getControl(FloatControl.Type.MASTER_GAIN);
volume.setValue(1.0f); // Reduce volume by 10 decibels.
play.start();
}
As, has already begin stated, you need to prevent the main thread from exiting, as this will cause the JVM to terminate.
Clip#start is not a blocking call, meaning that it will return (soon) after it is called.
I have no doubt that there are many ways to approach this problem and this is just a simple example of one of them.
public class PlayMusic {
public static void main(String[] args) throws InterruptedException {
Clip play = null;
try {
File in = new File("C:\\Users\\Public\\Music\\Sample Music\\Kalimba.wav");
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(in);
play = AudioSystem.getClip();
play.open(audioInputStream);
FloatControl volume = (FloatControl) play.getControl(FloatControl.Type.MASTER_GAIN);
volume.setValue(1.0f); // Reduce volume by 10 decibels.
play.start();
// Loop until the Clip is not longer running.
// We loop this way to allow the line to fill, otherwise isRunning will
// return false
//do {
// Thread.sleep(15);
//} while (play.isRunning());
play.drain();
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
ex.printStackTrace();
} finally {
try {
play.close();
} catch (Exception exp) {
}
}
System.out.println("...");
}
}
The actual solution will depend on your needs.
Java's sound Clip requires an active Thread to play the audio input file otherwise the application exits before the file can be played. You could add
JOptionPane.showMessageDialog(null, "Click OK to stop music");
after calling start.
The proper way to play the audio clip is to drain the line as explained in Playing Back Audio.
So your main should look like this:
public static void main(String[] args) throws IOException,
UnsupportedAudioFileException, LineUnavailableException
{
File in = new File("C:\\Users\\Sandra\\Desktop\\music\\rags.wav");
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(in);
Clip play = AudioSystem.getClip();
play.open(audioInputStream);
FloatControl volume= (FloatControl) play.getControl(FloatControl.Type.MASTER_GAIN);
volume.setValue(1.0f); // Reduce volume by 10 decibels.
play.start();
play.drain();
play.close();
}
play.drain() blocks until all the data is played.
Here playing a clip
public static void main(String[] args) throws Exception {
File in = new File("C:\\Users\\Sandra\\Desktop\\music\\rags.wav");
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(in);
Clip play = AudioSystem.getClip();
play.open(audioInputStream);
FloatControl volume= (FloatControl)play.getControl(FloatControl.Type.MASTER_GAIN);
volume.setValue(1.0f); // Reduce volume by 10 decibels.
play.start();
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!");
}
});
}
Your program is terminating before the sound has the time to be played. I would do play.start(); in some threading way (invokeLater, ...), and also find a way to wait until the sound has finished (Reimeus suggested one).
A lead :
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
...
play.start();
JOptionPane.showMessageDialog(null, "Click OK to stop music");
}
});
}
If you just want to play an audio, here's a way.
The audioFileDirectory String variable needs the correct path to your audio file, otherwise an exception will be thrown and the program won't run.
Example of having the right audio file directory in a project if using an IDE:
Make a folder inside src folder, e.g: "music" and put an audio file there
audioFileDirectory = "/music/name_of_audio_file";
The important part for an audio to play is that the main thread of the program needs somehow to be "alive", so the line
Thread.sleep(audio.getMicrosecondLength()/1000);
is where the main thread is "alive", and the argument audio.getMicrosecondLength()/1000 is the time that will be "alive", which is the whole length of the audio file.
public class AudioTest
{
void playAudio() throws Exception
{
String audioFileDirectory = "your_audioFileDirectory";
InputStream is = getClass().getResourceAsStream(audioFileDirectory);
BufferedInputStream bis = new BufferedInputStream(is);
AudioInputStream ais = AudioSystem.getAudioInputStream(bis);
Clip audio = AudioSystem.getClip();
audio.open(ais);
audio.loop(Clip.LOOP_CONTINUOUSLY);
audio.start();
Thread.sleep(audio.getMicrosecondLength()/1000);
audio.close();
} // end playAudio
public static void main(String[] args)
{
try
{
new AudioTest().playAudio();
}
catch (Exception e)
{
System.out.println("Class: " + e.getClass().getName());
System.out.println("\nMessage:\n" + e.getMessage() + "\n");
e.printStackTrace();
}
} // end main
} // end class AudioTest

Categories