I have recently been learning how to add sounds in java. Currently, I have this code that works, but it isn't always playing at the right time, or sometimes it doesn't even play at all. How could I get the sound to play each time the play() method is fired at the right timing? This happens every time I click on a component, by the way.
public class Sound {
private File sndFile0;
private AudioInputStream au;
private Clip cl;
private DataLine.Info info;
public Sound() {
try {
sndFile0 = new File(getClass().getResource("/sound/vir1.wav").toURI());
au = AudioSystem.getAudioInputStream(sndFile0);
info = new DataLine.Info(Clip.class, au.getFormat());
cl = (Clip) AudioSystem.getLine(info);
cl.open(au);
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException | URISyntaxException e) {
e.printStackTrace();
}
}
public void play() {
cl.start();
cl.setFramePosition(0);
}
}
Solved. What I did was I went ahead and loaded the sound file each time the component was clicked on.
Related
I am trying to use Javax.sound to play a .wav file.
Everything works fine, the file plays as expected and in the end I close the Clip and I close the AudioInputStream. However, the file remains locked (in use) after that and I cannot touch it without getting an exception: java.nio.file.FileSystemException: alerting.wav: The process cannot access the file because it is being used by another process.
A sample of code is below:
static private class SoundThread extends Thread implements LineListener {
private boolean playCompleted;
private int cycles;
public SoundThread(int repeats) {
cycles = repeats;
}
#Override
public void run() {
Clip clip;
AudioInputStream inputStream;
File soundFile = new File("alerting.wav");
try {
inputStream = AudioSystem.getAudioInputStream(soundFile);
try {
clip = AudioSystem.getClip();
clip.addLineListener(this);
clip.open(inputStream);
while(cycles > 0) {
playCompleted = false;
clip.setFramePosition(0);
clip.start();
while(!playCompleted) {
Thread.sleep(1000);
}
Thread.sleep(audioRepeatTime * 1000);
cycles--;
}
//clip.drain();
clip.close();
inputStream.close();
System.out.println("All closed");
try {
this.finalize();
} catch (Throwable ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (Exception ex) {
Main.syslog(Level.WARNING, "E1001 could not play alert sound", ex);
} finally {
inputStream.close();
}
} catch (UnsupportedAudioFileException ex) {
Main.syslog(Level.WARNING, "E1001 could not play alert sound", ex);
} catch (IOException ex) {
Main.syslog(Level.WARNING, "E1001 could not play alert sound", ex);
}
}
#Override
public void update(LineEvent event) {
LineEvent.Type type = event.getType();
System.out.println("Event: " + type);
if(type == LineEvent.Type.STOP) {
playCompleted = true;
} else if (type == LineEvent.Type.CLOSE) {
System.out.println("listener closed");
}
}
}
public static void PlayAlertSound() {
if(enableAudio) {
SoundThread st = new SoundThread(audioLoops);
st.start();
}
}
public static void PlayAlertSound(int repeats) {
if(enableAudio) {
SoundThread st = new SoundThread(repeats);
st.start();
}
}
In the Java threads list I see "Java Sound Event Dispatcher" running. I think this is what keeps the file locked.
Any idea how can I fix this? Thanks
The API for Clip states:
Note that some lines, once closed, cannot be reopened. Attempts to
reopen such a line will always result in a LineUnavailableException.
I'm going to make a couple additional suggestions.
Instead of using File, a better way to load audio resources is with the class.getResource method. This method returns a URL which you can then pass as your argument to the AudioSystem.getAudioInputStream method.
I'm not clear what you are trying to do, but I also recommend some further changes to your code. Initializing and playing a Clip in the same method is not generally done, as it goes against the intended use of the Clip. A Clip is meant for sounds that can be held in memory. So, make your Clip an instance variable. Then, place the code that loads and opens the Clip in its own method. And put the code that calls start or loop in a separate method or methods, and don't close the Clip at the end of playing unless you are sure you are not going to ever play it again.
If you use clip.loop, you don't have to bother with listeners and count iterations.
Instead of:
//...
AudioInputStream inputStream;
File soundFile = new File("alerting.wav");
try {
inputStream = AudioSystem.getAudioInputStream(soundFile);
// ...
}
// ...
Try this:
//...
AudioInputStream inputStream;
File soundFile = new File("alerting.wav");
try {
byte[] bytes = Files.readAllBytes(soundFile.toPath());
inputStream = AudioSystem.getAudioInputStream(new ByteArrayInputStream(bytes));
// ...
}
// ...
Problem; Only hearing one sound clip when executed. After one sound has played the other doesn't play & neither can play at the same time.
Result; To be able to play 2 sounds at the same time.
Code:
import java.io.*;
import javax.sound.sampled.*;
public class ThreadPlay extends Thread {
private String filename; // The name of the file to play
private boolean finished; // A flag showing that the thread has finished
private ThreadPlay(String fname) {
filename = fname;
finished = false;
}
public static void main(String[] args) {
ThreadPlay s1 = new ThreadPlay("soundClip1.wav");
ThreadPlay s2 = new ThreadPlay("soundClip2.wav");
s1.start();
s2.start();
while (!s1.finished || !s2.finished);
System.exit(0); // Java Sound bug fix...
}
public void run() {
try {
File file = new File(filename);
AudioInputStream stream = AudioSystem.getAudioInputStream(file);
AudioFormat format = stream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip clip = (Clip)AudioSystem.getLine(info);
clip.open(stream);
clip.start();
Thread.sleep(100);
while (clip.isRunning()) { Thread.sleep(100); }
clip.close();
}
catch (Exception e) { }
finished = true;
}
}
Audio Lines:
AudioSystem.getMixerInfo() results in:
[Ljavax.sound.sampled.Mixer$Info;#52cc8049
Array length: 7
Contents:
PulseAudio Mixer, version 0.02
default [default], version 4.4.0-66-generic
PCH [plughw:0,0], version 4.4.0-66-generic
PCH [plughw:0,1], version 4.4.0-66-generic
PCH [plughw:0,3], version 4.4.0-66-generic
PCH [plughw:0,7], version 4.4.0-66-generic
Port PCH [hw:0], version 4.4.0-66-generic
For each mixer, AudioSystem.getMixer(AudioSystem.getMixerInfo()[x])
Results:
org.classpath.icedtea.pulseaudio.PulseAudioMixer#685f4c2e
com.sun.media.sound.DirectAudioDevice#7a07c5b4
com.sun.media.sound.DirectAudioDevice#5ce65a89
com.sun.media.sound.DirectAudioDevice#1de0aca6
com.sun.media.sound.DirectAudioDevice#443b7951
com.sun.media.sound.DirectAudioDevice#45283ce2
com.sun.media.sound.PortMixer#4d76f3f8
Imports:
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
Run method:
public void run() {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(this.getClass().getResource("NameOfFile.wav"));
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
clip.loop(Clip.LOOP_CONTINUOUSLY); // There are several different amounts of time you can loop it, so you can change this if you want, or you can just use clip.stop() whenever you want.
} catch (Exception ex) {
ex.printStackTrace();
}
}
If you use this and piece of code over multiple threads, it should work. If I am correct in assuming that you are initiating this piece of code twice, once for each thread, then this should work. I hope that this helps.
Fixed:
public void run() {
try {
File file = new File(filename);
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
DataLine.Info info = new DataLine.Info(Clip.class, audioInputStream.getFormat());
Clip clip = (Clip)AudioSystem.getLine(info);
clip.open(audioInputStream);
clip.start();
clip.loop(Clip.LOOP_CONTINUOUSLY); // There are several different amounts of time you can loop it, so you can change this if you want, or you can just use clip.stop() whenever you want.
} catch (Exception ex) {
ex.printStackTrace();
}
finished = true;
}
Also, if you're running Ubuntu like myself you need to remove OpenJDK/OpenJRE and set SunJDK/SunJRE as Default.
I am rewriting my AudioManager class for my school project and I encountered a problem. My professor told me to load all my resources with the Try-with-resources block instead of using try/catch ( See code below ). I am using the Clip class from javax.sound.sampled.Clip and everything works perfectly with my PlaySound(String path) method that uses try/catch/ if I don't close() the Clip. I know that if I close() the Clip I can't use it anymore. I have read the Oracle Docs for Clip and Try-with-resources but I could not find a solution. So What I would like to know is:
Is it possible to use the Try-with-resource block to play/hear the sound from the clip before it closes?
// Uses Try- with resources. This does not work.
public static void playSound(String path) {
try {
URL url = AudioTestManager.class.getResource(path);
try (Clip clip = AudioSystem.getClip()){
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
clip.open(ais);
clip.start();
}
} catch( LineUnavailableException | UnsupportedAudioFileException | IOException e) {
e.printStackTrace();}
}
// Does not use Try- with resources. This works.
public static void playSound2(String path) {
Clip clip = null;
try {
URL url = AudioTestManager.class.getResource(path);
clip = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
clip.open(ais);
clip.start();
}
catch( LineUnavailableException | UnsupportedAudioFileException | IOException e) {
e.printStackTrace();}
finally {
// if (clip != null) clip.close();
}
}
Thanks in advance!
The problem is that try-with-resources block will automatically close the Clip created in it when the block finishes causing the playback to stop.
In your other example since you don't close it manually, the playback can continue.
If you want to close the Clip when it finished playing, you can add a LineListener to it with the addLineListener() and close it when you receive a STOP event like this:
final Clip clip = AudioSystem.getClip();
// Configure clip: clip.open();
clip.start();
clip.addLineListener(new LineListener() {
#Override
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP)
clip.close();
}
});
Okay so I'm get an error with this method that uses Files.toCopy it says that the file is already being used.
Files.copy( tempClip.toPath(), wavFile.toPath(), StandardCopyOption.REPLACE_EXISTING );
This is the method that opens the file. It copies fine when I don't use this method it gives the error when I do use this method. current.track below references the wavFile above. I thought I closed everything using the file with audioStream.close() and audioClip.close().
if ( e.getSource() instanceof QuoteButton) {
QuoteButton current = (QuoteButton)e.getSource();
try {
audioStream = AudioSystem.getAudioInputStream(current.track);
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
audioClip = (Clip) AudioSystem.getLine(info);
audioClip.open(audioStream);
audioClip.start();
audioClip.addLineListener(new LineListener() {
#Override
public void update(LineEvent event) {
if(event.getType() == LineEvent.Type.STOP){
audioClip.close();
}
}
});
audioStream.close();
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e1) {
e1.printStackTrace();
}
}
You close the audioclip in a listener so it's not actually called until you get LineEvent.Type.STOP
Never mind I had a privacy leak. Fixed it.
I have been working for days to try to fix my program. It plays a song once successfully, but it cannot re-play the song.
Weirdly enough, when attempting to create an short, self-contained example, I found that the same code can play a song, stop, then play a different song, but will not play the same song twice in a row. Given that on my app I don't know if the user will chose the same song again, so the stream must be closed and re-opened.
Here is an example demonstrating broken code(will not play song again):
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import java.io.IOException;
public class test{
static Clip musicplayer;
static AudioInputStream currentSong;
public static void main(String[] args){
try{
musicplayer = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.getAudioInputStream(new test().getClass().getResource("test.wav"));
playMusic(ais);
System.out.println("Playing Music");
Thread.sleep(4000);
stopMusic();
System.out.println("Stopping Music");
Thread.sleep(3000);
playMusic(ais);
System.out.println("Playing Music for the Second time");
Thread.sleep(5000);
System.out.println("Finished Program");
}catch(Exception ex){ex.printStackTrace();}
}
public static void playMusic(AudioInputStream music){
if(music == null)
return;
if(currentSong != null){
if(currentSong.equals(music))
return;
}
currentSong = music;
try {
musicplayer.setFramePosition(0);
musicplayer.stop();
musicplayer.open(currentSong);
} catch (LineUnavailableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
musicplayer.loop(Clip.LOOP_CONTINUOUSLY);
}
public static void stopMusic(){
musicplayer.close();
}
}
If I add another AudioInputStream in, and play that as my second song, it works fine.
You have two problems in this piece of code
current song is never reset so if you try to play the same stream twice it will just abort.
...
if(currentSong != null){
if(currentSong.equals(music))
return;
}
...
To clear it.
public static void stopMusic(){
musicplayer.close();
currentSong = null; // we do not have a current song anymore.
}
The other problem is that you are not reseting your input stream.
The simplest way is to just reload it. Streams are not array that you can give to something and it will magically start at the beginning. Anything accessing a Stream can only get whatever is next, if you give something a Stream where the next bit is the end then nothing will happen.
AudioInputStream ais = AudioSystem.getAudioInputStream(new test().getClass().getResource("test.wav"));
playMusic(ais);
ais = AudioSystem.getAudioInputStream(new test().getClass().getResource("test.wav"));
playMusic(ais);
one thing to be aware of is that AudioInputStream does not implement equals so
AudioSystem.getAudioInputStream(new test().getClass().getResource("test.wav")).equals( AudioSystem.getAudioInputStream(new test().getClass().getResource("test.wav")))
will evaluate to false.