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.
Related
I can set the default File Name: in a JFileChooser window using:
fileChooser.setSelectedFile();
I was wondering if it is also possible to select it, so that if you want to save the file as something else you can immediately start to overtype it. Thanks for any help on this.
package filetest;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
#SuppressWarnings("serial")
class Editor {
public static class TextClass extends JTextArea {
FileClass fileClass = new FileClass();
public void setKeyboardShortcuts() {
fileClass.setKeyboardShortcuts();
}
private class FileClass {
private File directory;
private String filepath = "";
private String filename = "";
private void setKeyboardShortcuts() {
Action ctrlo = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
openFile();
} catch (UnsupportedEncodingException e1) {
}
}
};
getInputMap().put(KeyStroke.getKeyStroke("ctrl O"), "ctrlo");
getActionMap().put("ctrlo", ctrlo);
Action ctrls = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
saveFile();
} catch (UnsupportedEncodingException e1) {
}
}
};
getInputMap().put(KeyStroke.getKeyStroke("ctrl S"), "ctrls");
getActionMap().put("ctrls", ctrls);
}
private String selectFile(String fileaction) throws FileNotFoundException {
JFileChooser filechooser = new JFileChooser();
if (directory != null) {
filechooser.setCurrentDirectory(directory);
} else {
filechooser.setCurrentDirectory(new File("."));
}
filechooser.setSelectedFile(new File(filepath));
int r = 0;
if (fileaction.equals("openfile"))
r = filechooser.showDialog(new JPanel(), "Open file");
else
r = filechooser.showDialog(new JPanel(), "Save file");
if (r == JFileChooser.APPROVE_OPTION) {
try {
directory = filechooser.getSelectedFile().getParentFile();
filename = filechooser.getSelectedFile().getName();
return filename;
} catch (Exception exception) {
return "";
}
} else {
return "";
}
}
private void openFile() throws UnsupportedEncodingException {
try {
String filestr = selectFile("openfile");
if (filestr.equals(""))
return;
else
filepath = filestr;
} catch (FileNotFoundException ex) {
Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void saveFile() throws UnsupportedEncodingException {
try {
String filestr = selectFile("savefile");
if (filestr.equals(""))
return;
else
filepath = filestr;
} catch (FileNotFoundException ex) {
Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
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(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
createAndShowGui();
}
});
}
private static void createAndShowGui() {
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
JTextArea textArea = new TextClass();
frame.add(textArea);
((TextClass) textArea).setKeyboardShortcuts();
frame.setVisible(true);
}
}
It does that by default on the machine I'm typing from:
package stackoverflow;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
*
* #author ub
*/
public class StackOverflow
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "gif","png");
chooser.setFileFilter(filter);
chooser.setSelectedFile(new File("C:\\Users\\ub\\Pictures\\Capt.PNG"));
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION)
System.out.println("You chose to open this file: "+chooser.getSelectedFile().getName());
}
}
It's because when you first call .setSelectedFile your filepath is an empty string.
You set your filepath variable after having shown the file chooser to the user.
If you print to console the string value of filepath, right before invoking .showDialog, you should see this.
The problem seems to be caused by these lines:
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(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
If they are removed, the file name is highlighted as in Unai Vivi's example.
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.
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);
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();
}
}
}
I am trying to play a *.wav file with Java. I want it to do the following:
When a button is pressed, play a short beep sound.
I have googled it, but most of the code wasn't working. Can someone give me a simple code snippet to play a .wav file?
Finally I managed to do the following and it works fine
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
public class MakeSound {
private final int BUFFER_SIZE = 128000;
private File soundFile;
private AudioInputStream audioStream;
private AudioFormat audioFormat;
private SourceDataLine sourceLine;
/**
* #param filename the name of the file that is going to be played
*/
public void playSound(String filename){
String strFilename = filename;
try {
soundFile = new File(strFilename);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
try {
audioStream = AudioSystem.getAudioInputStream(soundFile);
} catch (Exception e){
e.printStackTrace();
System.exit(1);
}
audioFormat = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
try {
sourceLine = (SourceDataLine) AudioSystem.getLine(info);
sourceLine.open(audioFormat);
} catch (LineUnavailableException e) {
e.printStackTrace();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
sourceLine.start();
int nBytesRead = 0;
byte[] abData = new byte[BUFFER_SIZE];
while (nBytesRead != -1) {
try {
nBytesRead = audioStream.read(abData, 0, abData.length);
} catch (IOException e) {
e.printStackTrace();
}
if (nBytesRead >= 0) {
#SuppressWarnings("unused")
int nBytesWritten = sourceLine.write(abData, 0, nBytesRead);
}
}
sourceLine.drain();
sourceLine.close();
}
}
Here is the most elegant form I could come up without using sun.*:
import java.io.*;
import javax.sound.sampled.*;
try {
File yourFile;
AudioInputStream stream;
AudioFormat format;
DataLine.Info info;
Clip clip;
stream = AudioSystem.getAudioInputStream(yourFile);
format = stream.getFormat();
info = new DataLine.Info(Clip.class, format);
clip = (Clip) AudioSystem.getLine(info);
clip.open(stream);
clip.start();
}
catch (Exception e) {
//whatevers
}
Shortest form (without having to install random libraries) ?
public static void play(String filename)
{
try
{
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File(filename)));
clip.start();
}
catch (Exception exc)
{
exc.printStackTrace(System.out);
}
}
The only problem is there is no good way to make this method blocking to close and dispose the data after *.wav finishes.
clip.drain() says it's blocking but it's not. The clip isn't running RIGHT AFTER start().
The only working but UGLY way I found is:
// ...
clip.start();
while (!clip.isRunning())
Thread.sleep(10);
while (clip.isRunning())
Thread.sleep(10);
clip.close();
You can use an event listener to close the clip after it is played
import java.io.File;
import javax.sound.sampled.*;
public void play(File file)
{
try
{
final Clip clip = (Clip)AudioSystem.getLine(new Line.Info(Clip.class));
clip.addLineListener(new LineListener()
{
#Override
public void update(LineEvent event)
{
if (event.getType() == LineEvent.Type.STOP)
clip.close();
}
});
clip.open(AudioSystem.getAudioInputStream(file));
clip.start();
}
catch (Exception exc)
{
exc.printStackTrace(System.out);
}
}
The snippet here works fine, tested with windows sound:
public static void main(String[] args) {
AePlayWave aw = new AePlayWave( "C:\\WINDOWS\\Media\\tada.wav" );
aw.start();
}
A class that will play a WAV file, blocking until the sound has finished playing:
class Sound implements Playable {
private final Path wavPath;
private final CyclicBarrier barrier = new CyclicBarrier(2);
Sound(final Path wavPath) {
this.wavPath = wavPath;
}
#Override
public void play() throws LineUnavailableException, IOException, UnsupportedAudioFileException {
try (final AudioInputStream audioIn = AudioSystem.getAudioInputStream(wavPath.toFile());
final Clip clip = AudioSystem.getClip()) {
listenForEndOf(clip);
clip.open(audioIn);
clip.start();
waitForSoundEnd();
}
}
private void listenForEndOf(final Clip clip) {
clip.addLineListener(event -> {
if (event.getType() == LineEvent.Type.STOP) waitOnBarrier();
});
}
private void waitOnBarrier() {
try {
barrier.await();
} catch (final InterruptedException ignored) {
} catch (final BrokenBarrierException e) {
throw new RuntimeException(e);
}
}
private void waitForSoundEnd() {
waitOnBarrier();
}
}
Another way of doing it with AudioInputStream:
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
public class CoreJavaSound extends Object implements LineListener {
File soundFile;
JDialog playingDialog;
Clip clip;
public static void main(String[] args) throws Exception {
CoreJavaSound s = new CoreJavaSound();
}
public CoreJavaSound() throws Exception {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
soundFile = chooser.getSelectedFile();
System.out.println("Playing " + soundFile.getName());
Line.Info linfo = new Line.Info(Clip.class);
Line line = AudioSystem.getLine(linfo);
clip = (Clip) line;
clip.addLineListener(this);
AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile);
clip.open(ais);
clip.start();
}
public void update(LineEvent le) {
LineEvent.Type type = le.getType();
if (type == LineEvent.Type.OPEN) {
System.out.println("OPEN");
} else if (type == LineEvent.Type.CLOSE) {
System.out.println("CLOSE");
System.exit(0);
} else if (type == LineEvent.Type.START) {
System.out.println("START");
playingDialog.setVisible(true);
} else if (type == LineEvent.Type.STOP) {
System.out.println("STOP");
playingDialog.setVisible(false);
clip.close();
}
}
}
A solution without java reflection DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat)
Java reflection decrease performance.
to run: java playsound absoluteFilePathTo/file.wav
import javax.sound.sampled.*;
import java.io.*;
public class playsound {
public static void main (String args[]) throws Exception {
playSound (args[0]);
}
public static void playSound () throws Exception {
AudioInputStream
audioStream = AudioSystem.getAudioInputStream(new File (filename));
int BUFFER_SIZE = 128000;
AudioFormat audioFormat = null;
SourceDataLine sourceLine = null;
audioFormat = audioStream.getFormat();
sourceLine = AudioSystem.getSourceDataLine(audioFormat);
sourceLine.open(audioFormat);
sourceLine.start();
int nBytesRead = 0;
byte[] abData = new byte[BUFFER_SIZE];
while (nBytesRead != -1) {
try {
nBytesRead =
audioStream.read(abData, 0, abData.length);
} catch (IOException e) {
e.printStackTrace();
}
if (nBytesRead >= 0) {
int nBytesWritten = sourceLine.write(abData, 0, nBytesRead);
}
}
sourceLine.drain();
sourceLine.close();
}
}
You can use AudioStream this way as well:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
public class AudioWizz extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L; //you like your cereal and the program likes their "serial"
static AudioWizz a;
static JButton playBuddon;
static JFrame frame;
public static void main(String arguments[]){
frame= new JFrame("AudioWizz");
frame.setSize(300,300);
frame.setVisible(true);
a= new AudioWizz();
playBuddon= new JButton("PUSH ME");
playBuddon.setBounds(10,10,80,30);
playBuddon.addActionListener(a);
frame.add(playBuddon);
frame.add(a);
}
public void actionPerformed(ActionEvent e){ //an eventListener
if (e.getSource() == playBuddon) {
try {
InputStream in = new FileInputStream("*.wav");
AudioStream sound = new AudioStream(in);
AudioPlayer.player.start(sound);
} catch(FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
I took #greenLizard's code and made it more robust.
I closed the AudioInputStream.
I used a BufferedInputStream. The AudioSystem getAudioInputStream was throwing an occasional IOException because the getAutoInputSytream method couldn't back up the input stream and start over.
Hopefully, there are no more exceptions to be found.
Here's the modified code. The ErrorDisplayDialog shows an exception as a JDialog in a Java Swing application. Just replace with e.printStackTrace();.
private void playWavFile(String fileName) {
InputStream inputStream = getClass().getResourceAsStream(fileName);
BufferedInputStream bufferedInputStream = new BufferedInputStream(
inputStream);
AudioInputStream audioStream = null;
AudioFormat audioFormat = null;
try {
audioStream = AudioSystem.getAudioInputStream(bufferedInputStream);
audioFormat = audioStream.getFormat();
} catch (UnsupportedAudioFileException e) {
new ErrorDisplayDialog(view.getFrame(),
"UnsupportedAudioFileException", e);
return;
} catch (IOException e) {
new ErrorDisplayDialog(view.getFrame(), "IOException", e);
return;
}
DataLine.Info info = new DataLine.Info(SourceDataLine.class,
audioFormat);
SourceDataLine sourceLine;
try {
sourceLine = (SourceDataLine) AudioSystem.getLine(info);
sourceLine.open(audioFormat);
} catch (LineUnavailableException e) {
new ErrorDisplayDialog(view.getFrame(), "LineUnavailableException",
e);
return;
}
sourceLine.start();
int nBytesRead = 0;
byte[] abData = new byte[128000];
while (nBytesRead != -1) {
try {
nBytesRead = audioStream.read(abData, 0, abData.length);
} catch (IOException e) {
new ErrorDisplayDialog(view.getFrame(), "IOException", e);
return;
}
if (nBytesRead >= 0) {
sourceLine.write(abData, 0, nBytesRead);
}
}
sourceLine.drain();
sourceLine.close();
try {
audioStream.close();
} catch (IOException e) {
new ErrorDisplayDialog(view.getFrame(), "IOException", e);
}
}