I am attempting to add an audio player to my application. Here's the code from the class that handles audio playing:
package me.pogostick29.audiorpg.audio;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
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;
import javax.sound.sampled.TargetDataLine;
public class AudioPlayer {
private AudioPlayer() { }
private static AudioPlayer instance = new AudioPlayer();
public static AudioPlayer getInstance() {
return instance;
}
private static ArrayList<BigClip> clips = new ArrayList<BigClip>();
private BigClip get(String name) {
for (BigClip clip : clips) {
if (clip.getName().equalsIgnoreCase(name)) return clip;
}
return null;
}
public void play(File file) {
try {
AudioInputStream audioIn = AudioSystem.getAudioInputStream(file);
BigClip clip = get(file.getName());
if (clip == null) {
BigClip newClip = new BigClip(file.getName());
clips.add(newClip);
clip = newClip;
}
clip.open(audioIn);
clip.start();
}
catch (Exception e) { e.printStackTrace(); }
}
}
However, when I try to run it using:
AudioPlayer.getInstance().play(new File("audio/people/blacksmith/blacksmith01a_new.wav"));
I get the following stack trace:
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1170)
at me.pogostick29.audiorpg.audio.AudioPlayer.play(AudioPlayer.java:38)
at me.pogostick29.audiorpg.person.people.Blacksmith.playDialogue(Blacksmith.java:12)
at me.pogostick29.audiorpg.AudioRPG.main(AudioRPG.java:33)
Here's the format I used when exporting the file with Audition.
Nevermind, I fixed it by using this library: http://www.javazoom.net/javalayer/javalayer.html
Related
I am attempting to play audio for a program and I need the AudioStream class and the AudioPlayer class, but when I attempt to import them Eclipse gives me an error.
Method where used:
public static void playMusic(String filepath) {
InputStream music;
try {
music = new FileInputStream(new File(filepath));
AudioStream audio = new AudioStream(music);
AudioPlayer.player.start(audio);
} catch(Exception e) {
JOptionPane.showMessageDialog(null, "Error");
}
}
Imports:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.swing.JOptionPane;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
I'm trying to have my program print a few "funny" images whenever it detects motion. Everything works by itself but when I put the if(detection == true) statement into the program, the variable doesn't update. How could I get it to update inside of the motionDetected function?
I've tried using boolean and int for the variable but I think it could be with the way I've structured it.
package printstuff;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.function.Function;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamMotionDetector;
import com.github.sarxos.webcam.WebcamMotionEvent;
import com.github.sarxos.webcam.WebcamMotionListener;
/**
* Detect motion.
*
* #author Bartosz Firyn (SarXos)
*/
public class DetectMotion implements WebcamMotionListener {
public static boolean detection = false;
public DetectMotion() {
//creates a webcam motion detector
WebcamMotionDetector detector = new WebcamMotionDetector(Webcam.getDefault());
detector.setInterval(100); // one check per 100 ms
detector.addMotionListener(this);
detector.start();
}
#Override
public void motionDetected(WebcamMotionEvent wme) {
//detects motion and should change the detection variable
System.out.println("Detected motion");
detection = true;
}
public static void main(String[] args) throws IOException, Exception {
new DetectMotion();
System.in.read(); // keep program open
final String[] catImages = new String[4];
//all the images
catImages[0] = "https://i.ytimg.com/vi/3v79CLLhoyE/maxresdefault.jpg";
catImages[1] = "https://i.imgur.com/RFS6RUv.jpg";
catImages[2] = "https://kiwifarms.net/attachments/dozgry5w4ae3cut-jpg.618924/";
catImages[3] = "https://www.foodiecrush.com/wp-content/uploads/2017/10/Instant-Pot-Macaroni-and-Cheese-foodiecrush.com-019.jpg";
//statement does not work..
if(detection == true)
{
for(int i=0; i<4; i++)
{
//saves the picture inside of the array to image.jpg
String imageUrl = catImages[i];
String destinationFile = "image.jpg";
saveImage(imageUrl, destinationFile);
//sends print job to printer
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new Copies(1));
PrintService pss[] = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.GIF, pras);
if (pss.length == 0)
throw new RuntimeException("No printer services available.");
PrintService ps = pss[0];
System.out.println("Printing to " + ps);
DocPrintJob job = ps.createPrintJob();
FileInputStream fin = new FileInputStream("image.jpg");
Doc doc = new SimpleDoc(fin, DocFlavor.INPUT_STREAM.GIF, null);
job.print(doc, pras);
fin.close();
java.util.concurrent.TimeUnit.SECONDS.sleep(15);
}
}
}
public static void saveImage(String imageUrl, String destinationFile) throws IOException {
//converts url into image
URL url = new URL(imageUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
}
package net.NitroCruze.mrpg.baseengine.music;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
public class CPSound implements Runnable{
AudioInputStream as1;
AudioFormat af;
Clip clip1;
DataLine.Info info;
Line line1;
public CPSound() {
Thread soundThread;
soundThread = new Thread(this, "Sound");
soundThread.start();
}
public void play() {
try{
as1 = AudioSystem.getAudioInputStream(new FileInputStream(new File("/res/music.wav")));
af = as1.getFormat();
clip1 = AudioSystem.getClip();
info = new DataLine.Info(Clip.class, af);
line1 = AudioSystem.getLine(info);
}
catch(Exception e)
{
}
if ( ! line1.isOpen() )
{
try
{
clip1.open(as1);
}
catch (Exception e)
{
}
clip1.loop(Clip.LOOP_CONTINUOUSLY);
clip1.start();
}
}
public void run()
{
play();
}
}
Why does this not work? It gives me a NullPointerException?
I found out why it wasn't working! I had put "/" before 'res/music.wav' which caused the file loading system to think I was loading from a DRIVE (eg C:/ F:/), but there was nothing before that / so it thought it was loading from a null drive, which cannot exist.
I've tried to search similiar question to this, but couldn't find. I don't know how i can stop my sound when button is released, and also, i don't know how to loop sound only one by one, when i hold button it plays again while previous loop is still playing, and the sound is becoming a loop from ∞ sounds.
Here's the code:
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Component;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.net.MalformedURLException;
import java.util.ArrayList;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class test {
String b[]={"Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M"};
Action[] actions = new AbstractAction[26];
public test() throws Exception {
JFrame frame = new JFrame();
JButton[] buttons = new JButton[26];
for(int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton(b[i]);
buttons[i].setSize(80, 80);
buttons[i].addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
System.out.println(e.getKeyChar());
playSound(new File("loopbase/loop1/"+e.getKeyChar()+".wav"));
}
public void keyReleased(KeyEvent e){
}
});
frame.add(buttons[i]);
}
JPanel contentPane = (JPanel)frame.getContentPane();
frame.setLayout(new GridLayout(3, 5, 5, 3));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
try {
new test();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void playSound(File soundName)
{
try
{
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundName.getAbsoluteFile( ));
Clip clip = AudioSystem.getClip( );
clip.open(audioInputStream);
clip.start( );
}
catch(Exception ex)
{
System.out.println("Error with playing sound.");
ex.printStackTrace( );
}
}
}
Anyone can help me with this issue?
I don't know how i can stop my sound when button is released?
You can stop the the clip by using DataLine#stop(). Just keep the reference of last played clip and call below line to stop it.
clip.stop();
Note: You can store it somewhere in static variable.
Sample code:
private static Clip clip;
...
public void keyReleased(KeyEvent e) {
if (clip != null) {
clip.stop();
}
}
...
public void playSound(File soundName) {
...
clip = AudioSystem.getClip();
...
}
When I hold the Button it plays again while previous loop is still playing.
This is because for every keyPress you are creating a new File object. That should be avoided.
To stop sound:
I would add a boolean parameter to playsound method. And depending upon the parameter passed I would call clip.start() or clip.stop() (superclass DataLine has a stop method) .
Call playsound(filename,false); in keyReleased.
public void playSound(File soundName , boolean start)
{
try
{
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundName.getAbsoluteFile( ));
Clip clip = AudioSystem.getClip( );
clip.open(audioInputStream);
if(start == true)
clip.start();
else
clip.stop();
}
catch(Exception ex)
{
System.out.println("Error with playing sound.");
ex.printStackTrace( );
}
}
I'm trying to play a .wav sound every time the user presses a button, but an exception gets thrown:
Exception in thread "Thread-0" java.lang.IllegalArgumentException: Invalid format
at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.createStream(PulseAudioDataLine.java:142)
at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.open(PulseAudioDataLine.java:99)
at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.open(PulseAudioDataLine.java:283)
at org.classpath.icedtea.pulseaudio.PulseAudioClip.open(PulseAudioClip.java:402)
at org.classpath.icedtea.pulseaudio.PulseAudioClip.open(PulseAudioClip.java:453)
at Uber.play(Uber.java:534)
at Uber$5.run(Uber.java:340)
at java.lang.Thread.run(Thread.java:724)
Here's the code:
//Play Audio File
public void play(String file) throws LineUnavailableException, UnsupportedAudioFileException, IOException
{
AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File(file));
Clip clip = AudioSystem.getClip();
clip.open(inputStream);
clip.start();
}
I managed to get it working.
This is the code that I used. Keep in mind that I needed this just to play a short beep.wav sound. It seems to have some trouble with longer sound files. Let me know if it works for you guys and if you manage to play longer sounds with this code.
public void play(String file) throws LineUnavailableException, UnsupportedAudioFileException, IOException
{
try
{
AudioInputStream inputStream = AudioSystem.getAudioInputStream(this.getClass().getResource(file));
AudioFormat format = inputStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip clip = (Clip)AudioSystem.getLine(info);
clip.open(inputStream);
clip.start();
}
catch (IOException | LineUnavailableException | UnsupportedAudioFileException e1)
{
e1.printStackTrace();
}
}
It's something wrong with the file path you are passing. When I use your same code getting the file from a JFileChooser it works fine. Test this out.
Also see the Javasound wiki tag for working with unsupported audio file types
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
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.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.SwingUtilities;
public class TestAudio {
public TestAudio() {
JButton button = new JButton("Choose file");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
File file = null;
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
}
String fileName = file.getAbsolutePath();
try {
play(fileName);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
JFrame frame = new JFrame();
frame.add(button);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(300, 300);
frame.setVisible(true);
}
public void play(String file) throws LineUnavailableException, UnsupportedAudioFileException, IOException {
AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File(file));
Clip clip = AudioSystem.getClip();
clip.open(inputStream);
clip.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TestAudio();
}
});
}
}