Playing a .wav file when the count is finished - java

I've made a countdown clock that works, but I want it to play a sound the countdown is finished. My problem is that I get a NullPointerException and I don't know how to solve it. Here's the code without the imports:
public class ReminderBeep {
Toolkit toolkit;
private String Path_to_sound = "sirenpolice5.wav";
public AudioClip audioclip;
Timer timer;
public ReminderBeep(int seconds) {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new RemindTask(), seconds * 1000);
}
class RemindTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
try {
URL url = this.getClass().getClassLoader().getResource(Path_to_sound);
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
} catch (MalformedURLException murle) {
System.out.println(murle);
} catch (LineUnavailableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(0);
}
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to countdown clock. Please type how many seconds you wanna count down from");
int sec = scan.nextInt();
new ReminderBeep(sec);
System.out.println("Counting");
}
}

Have found the problem I was missing a Thread.sleep(clip.getMicrosecondLength() / 1000);

Related

Background Music for a Java game

So I've been asked to help with a Java game and I've been given the Audio role. I get the audio to play but I need to get it to where I can stop the audio and start up a new audio string within another file that's calling it. Here's what I have;
import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
import javax.swing.*;
public class SoundTest{
// Constructor
public static void Run(String pen)throws InterruptedException {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Test Sound");
f.setSize(300, 200);
f.setVisible(false);
try {
// Open an audio input stream.
File soundFile = new File(pen);
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
}
and I have this that calls it
import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
import javax.swing.*;
public class SoundCall{
public static void main(String[] args)throws InterruptedException {
JFrame f = new JFrame();
SoundTest sound = new SoundTest();
sound.Run("Jskee_-_I_Am_Pharaoh_.wav");
JOptionPane.showMessageDialog(f,"Window","Cracker",JOptionPane.PLAIN_MESSAGE);
sound.stop;
sound.Run("Rejekt_-_Crank.wav");
}
}
First of all, declare your Clip outside of the Run function, like this: Clip clip; then just do clip = AudioSystem.getClip(); and finally, make a stop function in your SoundTest class that looks like this:
public boolean stop(int id) {
if (clips.get(id-1) != null) {
clips.get(id-1).stop();
return true;
}
return false;
}
Returning a boolean is for checking, so that your application is sure if it has stopped the music or not. This is what your full SoundTest file will look like afterwards:
import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
import javax.swing.*;
public class SoundTest{
private ArrayList<Clip> clips = new ArrayList<Clip>();
// Constructor
public void Run(String pen)throws InterruptedException {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Test Sound");
f.setSize(300, 200);
f.setVisible(false);
try {
// Open an audio input stream.
File soundFile = new File(pen);
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
clips.add(clip);
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
public boolean stop(int id) {
if (clips.get(id-1) != null) {
clips.get(id-1).stop();
return true;
}
return false;
}
}
And in your SoundCall class, simply do
if(sound.stop(1)) { //1 is an id, I made it so that it starts at 1, not 0.
System.out.println("Audio stopped.");
} else {
System.out.println("Audio has not stopped.");
}
The id is when the clip was called, kinda. If it was the first clip to be executed, the id is 1, if it was the second the id is 2 etc.

Starting and stopping music files in Java?

This is my sound class.
public class Sounds extends Thread {
private String filename;
private Position curPosition;
private final int EXTERNAL_BUFFER_SIZE = 524288;
enum Position {
LEFT, RIGHT, NORMAL
};
public Sounds(String wavFile) {
filename = wavFile;
curPosition = Position.NORMAL;
}
public Sounds(String wavfile, Position p) {
filename = wavfile;
curPosition = p;
}
public void run() {
File soundFile = new File(filename);
if (!soundFile.exists()) {
System.err.println(".wav 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();
}
}
}
And this is my ActionListener that I want to stop the music when the user clicks a button. The music plays on start up.
btnSound.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
btnSound.setVisible(false);
btnNoSound.setVisible(true);
new Sounds("Sounds/MenuMusic.wav").end();
}
});
I can get the music to play just fine, but I can't figure out how to stop it. I tried using .stop() and .end() but I was told they were deprecated. Anyone have any idea how I can do this? thanks.
You could use the clip class. This is my code for reading a .wav file and playing it:
try {
File file = new File(src); // src is the location of the file
AudioInputStream stream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(stream);
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
That was, clip.stop() will stop the clip. To reset the clip, use clip.setFramePosition(0). Note that clip does not need to be closed, because if clip.close() is called after clip.start(), the clip will not play.
Hope that's what you were looking for!
EDIT: Scoping
Using scoping in Java, if you declare a local variable in a method, you cannot access it outside of the method. If you want to access the clip outside of the main method, extract it to a field:
class Main {
static Clip clip;
public static void main (String... args) {
try {
File file...
clip = AudioSystem.getClip();
...
} catch...
}
}

Java, javazoom program for playing MP3 files(AdvancedPlayer), event.getFrame() is giving random things

I'm trying to write a program that plays .mp3 files, playing them works perfectly. But pausing is causing some trouble. When I pause the song (stop the song and ask for the frame) I get an incorrect value.
class PauseStartMP3Test {
private static AdvancedPlayer player;
private static int pausedOnFrame = 0;
private static boolean playing = false;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(true) {
String s = in.next();
if(!s.equals("")) {
if(!playing) {
playing = true;
play();
}
else {
player.stop();
}
}
}
}
public static void play() {
File file = null;
file = new File("C:\\Users\\Remco\\Desktop\\Programming\\musictest/throughglass.mp3");
try {
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
try {
player = new AdvancedPlayer(bis);
new Thread() {
public void run() {
try {
if(playing) {
player.setPlayBackListener(new PlaybackListener() {
#Override
public void playbackFinished(PlaybackEvent event) {
pausedOnFrame = event.getFrame();
System.out.println(pausedOnFrame);
playing = false;
}
});
player.play(pausedOnFrame, Integer.MAX_VALUE);
}
else {
player.stop();
}
}
catch (Exception e) {
System.out.println(e);
}
}
}.start();
} catch (JavaLayerException ex) {
System.out.println(ex);
}
} catch (FileNotFoundException ex) {
System.out.println(ex);
}
}

In Java, How do you stop a previous audio file when another audio file starts using key_events

I know about the clip.stop() method, however it doesn't seem to work within when I have it inside the key_events. It just causes an Error. Well I know why it causes the error. Because I'm asking it to essentially stop a clip that doesn't exist until a few lines later. But using this same logic or close to it if possible, how could I recode that so it knows to select the previous clip that was playing from a previous key_event. The functionality I'm intending for is: When F1 is pressed, a wav plays. When F2 is pressed, current wav STOPS, new wav STARTS. When F3 is pressed, current wav STOPS, new wav STARTS. Etc etc etc.
case KeyEvent.VK_F1:
try {
//stop any sound
clip.stop();
sample = AudioSystem.getAudioInputStream(getURL(filename));
//create a sound buffer
Clip clip = AudioSystem.getClip();
//load the audio file
clip.open(sample);
//play sample
clip.start();
} catch (MalformedURLException ez) {
} catch (IOException ez) {
} catch (LineUnavailableException ez) {
} catch (UnsupportedAudioFileException ez) {
} catch (Exception ez) { }
break;
case KeyEvent.VK_F2:
try {
//stop any sound
clip.stop();
sample = AudioSystem.getAudioInputStream(getURL(filename2));
//create a sound buffer
Clip clip = AudioSystem.getClip();
//load the audio file
clip.open(sample);
//play sample
clip.start();
} catch (MalformedURLException ez) {
} catch (IOException ez) {
} catch (LineUnavailableException ez) {
} catch (UnsupportedAudioFileException ez) {
} catch (Exception ez) { }
break;
case KeyEvent.VK_F3:
try {
//stop any sound
clip.stop();
sample = AudioSystem.getAudioInputStream(getURL(filename3));
//create a sound buffer
Clip clip = AudioSystem.getClip();
//load the audio file
clip.open(sample);
//play sample
clip.start();
} catch (MalformedURLException ez) {
} catch (IOException ez) {
} catch (LineUnavailableException ez) {
} catch (UnsupportedAudioFileException ez) {
} catch (Exception ez) { }
break;
case KeyEvent.VK_F4:
try {
//stop any sound
clip.stop();
sample = AudioSystem.getAudioInputStream(getURL(filename4));
//create a sound buffer
Clip clip = AudioSystem.getClip();
//load the audio file
clip.open(sample);
//play sample
clip.start();
} catch (MalformedURLException ez) {
} catch (IOException ez) {
} catch (LineUnavailableException ez) {
} catch (UnsupportedAudioFileException ez) {
} catch (Exception ez) { }
break;
case KeyEvent.VK_F5:
try {
//stop any sound
clip.stop();
sample = AudioSystem.getAudioInputStream(getURL(filename5));
//create a sound buffer
Clip clip = AudioSystem.getClip();
//load the audio file
clip.open(sample);
//play sample
clip.start();
} catch (MalformedURLException ez) {
} catch (IOException ez) {
} catch (LineUnavailableException ez) {
} catch (UnsupportedAudioFileException ez) {
} catch (Exception ez) { }
break;
case KeyEvent.VK_F6:
try {
//stop any sound
clip.stop();
sample = AudioSystem.getAudioInputStream(getURL(filename6));
//create a sound buffer
Clip clip = AudioSystem.getClip();
//load the audio file
clip.open(sample);
//play sample
clip.start();
} catch (MalformedURLException ez) {
} catch (IOException ez) {
} catch (LineUnavailableException ez) {
} catch (UnsupportedAudioFileException ez) {
} catch (Exception ez) { }
break;
case KeyEvent.VK_F7:
try {
//stop any sound
clip.stop();
sample = AudioSystem.getAudioInputStream(getURL(filename7));
//create a sound buffer
Clip clip = AudioSystem.getClip();
//load the audio file
clip.open(sample);
//play sample
clip.start();
} catch (MalformedURLException ez) {
} catch (IOException ez) {
} catch (LineUnavailableException ez) {
} catch (UnsupportedAudioFileException ez) {
} catch (Exception ez) { }
break;
Any help would be greatly appreciated :) Thanks
It's difficult to be 100% sure, but it looks like you are shadowing your variables...
clip.stop();
sample = AudioSystem.getAudioInputStream(getURL(filename));
//create a sound buffer
Clip clip = AudioSystem.getClip();
In fact, I'm not even sure how this would compile...
Define Clip as an instance variable, when you program is initialised, initialise the Clip at the same time.
You should be able to call stop at any time, but this will only reset the Clip back to the start of the current input. What you need to, also do, is close the Clip, which releases the internal resources been managed by the Clip for the current input...
KeyListeners are also notoriously troublesome and you should consider using Key Bindings as they provide you with the control to determine the focus level that the key events can be generated at, for example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestPlayer {
public static void main(String[] args) {
new TestPlayer();
}
public TestPlayer() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
try {
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (LineUnavailableException exp) {
exp.printStackTrace();
}
}
});
}
public class TestPane extends JPanel {
private Clip clip;
private List<File> playList;
private int index;
private JLabel label;
public TestPane() throws LineUnavailableException {
label = new JLabel("Play stuff");
add(label);
clip = AudioSystem.getClip();
File[] files = new File("A folder of music files").listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return file.getName().toLowerCase().endsWith(".wav");
}
});
playList = new ArrayList<>(Arrays.asList(files));
index = -1;
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "previous");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "next");
ActionMap am = getActionMap();
am.put("next", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
playNext();
}
});
am.put("previous", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
playPrevious();
}
});
}
public void playNext() {
index++;
if (index >= playList.size()) {
index = 0;
}
File file = playList.get(index);
play(file);
}
public void playPrevious() {
index--;
if (index < 0) {
index = playList.size() - 1;
}
File file = playList.get(index);
play(file);
}
public void play(File file) {
try {
stop();
label.setText(file.getName());
AudioInputStream sample = AudioSystem.getAudioInputStream(file);
clip.open(sample);
clip.start();
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException exp) {
exp.printStackTrace();
}
}
public void stop() {
clip.stop();
clip.close();
}
}
}

blocking thread when progressbar is running

Hello guys i want to make ProgressBar who will loading till the song starts ...
i have this code but the ProgressBar is starting when the song starts and also its maked to finish it about 5 sec. so please someone help me make it right ... Thanks :)
package passwordsaver1;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.net.URL;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.JOptionPane;
public final class Music extends javax.swing.JFrame {
void centreWindow() {
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - getWidth()) / 2);
int y = (int) ((dimension.getHeight() - getHeight()) / 2);
setLocation(x, y);
}
public Music(String mainAccName) {
initComponents();
centreWindow();
setTitle("PasswordSaver - Music");
this.mainAccName = mainAccName;
}
String mainAccName;
private void pitbullActionPerformed(java.awt.event.ActionEvent evt) {
try {
URL url = new URL("http://mini-mk-market.com/music/PitBulll.wav");
Clip clip = AudioSystem.getClip();
AudioInputStream ais;
ais = AudioSystem.getAudioInputStream(url);
clip.open(ais);
clip.loop(5);
clip.start();
new Thread(new Start()).start();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Can't find Internet Connection !");
}
}
// this is just for testing does the song will stop after clicking the new... but cant..
private void afrojackActionPerformed(java.awt.event.ActionEvent evt) {
try {
URL url = new URL("http://mini-mk-market.com/music/PitBulll.wav");
Clip clip = AudioSystem.getClip();
AudioInputStream ais;
ais = AudioSystem.getAudioInputStream(url);
clip.open(ais);
clip.loop(0);
clip.start();
new Thread(new Start()).start();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Can't find Internet Connection !");
}
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info:
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Music.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Music.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Music.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Music.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
//new Music().setVisible(true);
}
});
}
private class Start implements Runnable {
#Override
public void run() {
for (int x = 0; x < 101; x++) {
ProgressBar.setValue(x);
ProgressBar.repaint();
try {
Thread.sleep(50);
} catch (Exception ex) {
}
}
}
}
You may be looking for ProgressMonitorInputStream. There 's a discussion in How to Use Progress Monitors, and an example in ProgressMonitorDemo.

Categories