I am writing a programm and I added some background music to it.
However I would like to be able to stop the music by the click of a button.
I know how to add buttons and stuff however I don't know how to stop the music, I have tried a lot of things but just can't get it to work.
This is my code:
new Thread(new Runnable() {
public void run() {
try {
Clip Music = AudioSystem.getClip();
AudioInputStream BMG = AudioSystem.getAudioInputStream(
Main.class.getResourceAsStream("/Music/BackgroundMusic.wav"));
Music.open(BMG);
Music.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}).start();
If you could help that would be awesome!
Thank you in advance,
JS
Clip Music=null;
new Thread(new Runnable() {
public void run() {
try {
Clip Music = AudioSystem.getClip();
AudioInputStream BMG = AudioSystem.getAudioInputStream(
Main.class.getResourceAsStream("/Music/BackgroundMusic.wav"));
Music.open(BMG);
Music.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}).start();
//this goes inside the actionPerformed event of the button
if(Music!=null)Music.stop();
And as m0skit0 said you better start your variables with a lowercase letter,don't be a c# smug.
Related
I am currently creating virtual drum kit. Kinect is recording my moves and when I hit the virtual drum the program needs to play the sound of this drum. Currently my code to play music looks like that:
void playInstrumentSound(InstrumentModel instrument) {
if (instrument.getMedia() != null) {
new Thread() {
public void run() {
instrument.setPlaying(true);
MediaPlayer player = new MediaPlayer(instrument.getMedia());
player.setVolume(1);
player.play();
try {
Thread.sleep(properties.getSleepLength());
} catch (InterruptedException e) {
e.printStackTrace();
}
instrument.setPlaying(false);
player.dispose();
}
}.start();
}
}
InstrumentModel is my class that contains Media object that is initialized by using pathToSound which is path to .wav file in resources folder:
if (this.pathToSound != null) {
media = new Media(new File(this.pathToSound).toURI().toString());
}
Right now this code doesn't reach my expectations, because if I hit a drum then I can't hit it again for the properties.getSleepLength() value of time (now it is about 200ms). If I don`t make Thread sleep then I don't hear full sound.
For example, if the .wav file duration is 300ms and I make Thread.sleep(300) inside playInstrumentSound() method, then I can hear full sound but I can't play different sound for this 300ms. But if I make Thread.sleep(50) then I can hit it again almost instantly but I hear only 50ms of the .wav file.
I would like to be able to hit the drum almost instantly but also hear full sound of it. How can I reach that? Thanks in advance.
EDIT:
I just got an idea to change order inside playInstrumentSoundMethod:
void playInstrumentSound(InstrumentModel instrument) {
if (instrument.getMedia() != null) {
instrument.setPlaying(true);
MediaPlayer player = new MediaPlayer(instrument.getMedia());
player.setVolume(1);
player.play();
new Thread() {
public void run() {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
instrument.setPlaying(false);
}
}.start();
new Thread() {
public void run() {
try {
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
player.dispose();
}
}.start();
}
Now it should turn the sound off after 250ms and changes isPlaying flag after 50ms (if isPlaying flag is true then you can't hit a drum again). You think that it might work?
I have sound effects for a game. Upon the game frame opening, the first sound lags behind. After that sound plays, no more lag is experienced.
Here's my clip player:
public enum SoundEffect
{
WALL("ping_pong_8bit_plop"),
PADDLE("ping_pong_8bit_beeep"),
POINT("ping_pong_8bit_peeeeeep");
public static enum Volume
{
MUTE, UNMUTE
}
public static Volume volume = Volume.MUTE;
private Clip clip;
SoundEffect (String file)
{
try
{
AudioInputStream inputStream = AudioSystem.getAudioInputStream(this.getClass().getResource(file+".wav"));
AudioFormat format = inputStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
clip = (Clip)AudioSystem.getLine(info);
clip.open(inputStream);
}
catch (UnsupportedAudioFileException uae)
{
uae.printStackTrace();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
catch (LineUnavailableException lue)
{
lue.printStackTrace();
}
}
public void play()
{
if (volume != Volume.MUTE)
{
if (clip.isRunning())
clip.stop();
clip.flush();
clip.setFramePosition(0);
clip.start();
}
}
static void init()
{
values();
}
}
So when I call SoundEffect.WALL.play() for example, it plays fine overall, but the very first time it plays there is a huge lag spike. What can I do to solve this, preferably still using Clips?
I had the same bug, the first play of a clip was about 1-2 sec delayed, no matter when the play()-method is called. What I did is I played a clip in the main() method which is a half seccond long and contains nothing (no sound). This means that the play() method of the actual sound isn't called the first time, and for me, it works. Hope it helped.
Use a separate Thread
Thread music = new Thread(new Runnable() {
#Override public void run() { your code }
};
music.start();
My goal is to make a program that displays a pop up window with a single button called play. I am using an inner class and action listener. The button does in fact play the audio clip. Now what I would like to do is make it so every time I hit the play button it plays it from the beginning and I do not hear more than one instance of the clip being played in it's completion. Here is the code I have for the inner class only:
private class PlaySound implements ActionListener {
public void actionPerformed(ActionEvent e) {
String filename = "/Users/philipgouldman/Desktop/iPhoneRingtones/Dummy_Yeah.wav";
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File(filename)));
clip.setFramePosition(0);
clip.start();
} catch (Exception exc) {
exc.printStackTrace(System.out);
}
}
}
I would appreciate any tips or suggestions to achieve this goal. I read on the Clip Interface javadoc that if the user wants the action to restart to simply invoke stop following setFramePosition(0). I can't say I quite understand what that means. Can someone guide me in the right direction?
Move your Clip Object outside of this handle so that its state can be investigated later.
e.g.
private class PlaySound implements ActionListener {
private Clip clip = null;
public void actionPerformed(ActionEvent e) {
String filename = "/Users/philipgouldman/Desktop/iPhoneRingtones/Dummy_Yeah.wav";
try {
if (clip == null) {
clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File(filename)));
}
clip.setFramePosition(0);
clip.start();
} catch (Exception exc) {
exc.printStackTrace(System.out);
}
}
}
I have a button that plays this code when pressed:
public void music() throws UnsupportedAudioFileException, IOException {
try {
URL url = this.getClass().getResource("/audio/InGame01.mid");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
But, not only is the sound delayed (I'm assuming its because it has to read the sound file, and then play it), the button also becomes frozen until it finishes reading the sound clip. Is there a simple way to open the audio clip before the button is actually pressed, so that it already has it loaded? (clip.open(audioIn) is what I'm talking about.)
This is where the method is called(Button Listener):
try {
music();
} catch (UnsupportedAudioFileException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
I've found a working Sound class online and am using it to play sound in a game I'm making. However, I wanted to continuously play the file so I decided just to use a Swing Timer and it works, the only problem is my game window freezes and won't even let you exit it out without using task manager.
Can you please take a look at it and tell me where I went wrong? By the way main is just my object variable for my Sound class, and maindelay is just my int for the delay.
public static void loopSound(){
Timer maintime = new Timer(maindelay, new ActionListener(){
public void actionPerformed(ActionEvent e){
main.run();
}
});
maintime.start();
}
The Sound class I've found:
public class Sound extends Thread {
private String filename;
private Position curPosition;
private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb
enum Position {
LEFT, RIGHT, NORMAL
};
public Sound(String wavfile) {
filename = wavfile;
curPosition = Position.NORMAL;
}
public Sound(String wavfile, Position p) {
filename = wavfile;
curPosition = p;
}
public void run() {
File soundFile = new File(filename);
if (!soundFile.exists()) {
System.err.println("Wave file not found: " + filename);
return;
}
AudioInputStream audioInputStream = null;
try {
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
} catch (UnsupportedAudioFileException e1) {
e1.printStackTrace();
return;
} catch (IOException e1) {
e1.printStackTrace();
return;
}
AudioFormat format = audioInputStream.getFormat();
SourceDataLine auline = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
try {
auline = (SourceDataLine) AudioSystem.getLine(info);
auline.open(format);
} catch (LineUnavailableException e) {
e.printStackTrace();
return;
} catch (Exception e) {
e.printStackTrace();
return;
}
if (auline.isControlSupported(FloatControl.Type.PAN)) {
FloatControl pan = (FloatControl) auline
.getControl(FloatControl.Type.PAN);
if (curPosition == Position.RIGHT)
pan.setValue(1.0f);
else if (curPosition == Position.LEFT)
pan.setValue(-1.0f);
}
auline.start();
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
try {
while (nBytesRead != -1) {
nBytesRead = audioInputStream.read(abData, 0, abData.length);
if (nBytesRead >= 0)
auline.write(abData, 0, nBytesRead);
}
} catch (IOException e) {
e.printStackTrace();
return;
} finally {
auline.drain();
auline.close();
}
}
}
I'm guessing the sound last longer than 1 second. The int you pass to Timer is in milliseconds. It would seem to me that you are creating the sounds quicker than they can be played and this is clogging your application and blocking the UI (hence the "freeze").
I think using a Timer is the wrong way to repeatedly play the sound. You need instead to modify the sound file.
// as Sound
class RepeatSound {
...
public void run() {
// modify this condition to something meaningful
while (true) {
// as original Sound.run() in here
...
}
}
...
}
And call RepeatSound.start(). You must change that while(true) to exit with your application e.g. make it while (myFrame.visible()) to stop playing once the window is closed.
Some hints to solve the problem:
Swing Timer API states that a timer will repeat the notification to its listeners by default. It means you have an endless loop caused by this timer. See isRepeats() javadoc.
Consequently in each iteration a new thread playing a song is created which is not correct at all.
However as you don't have any interaction between swing components and played song you don't need a Swing timer actually. Just run your Song class in a separate thread than the EDT (Event Dispatch Thread) and it should be all right.
However, I wanted to continuously play the file...
As far as I can see in SourceDataLine interface API it extends from Line interface which allows you add LineListeners to listen LineEvents. Having said all this you may add a listener to restart the data line when it stops. I'd say it should look like something like this:
public class Sound extends Thread {
...
public void run()
...
auline.addLineListener(new LineListener() {
#Override
public void update(LineEvent e) {
if(e.getType() == LineEvent.Type.STOP && e.getLine().isOpen()) {
e.getLine().start();
}
}
});
auline.start();
...
}
...
}
Note: I really don't have time enough to play with this API so it's up to you test if it works. However I made an MP3 player for my cellphone using Java Mobile Media API and the approach was quite similar when I wanted to repeat the same song over again when it finishes.