Why isn't my program playing an audio clip? - java

Trying to loop an audio clip. Look right but i hear nothing.
Does local audio clip have to have the extension ".au"? or can i play aiff, mp3 or wav for example?
I'm really sorry if this is not properly explaned. I'm really new to this.
Tried to play sounds on my hard drive (.wav) (put in the same folder as my java program) AND of the internet.
An input dialog pops up and asks for an audio clip. Works fine. Here the user is supposed to write either a local file name or a web address.
I write (for local files) "file:myAudioclip.wav" or (for internet) "https://www....) but nothing plays.
import java.applet.*; //Importerar necessary packages
import java.net.*;
import javax.swing.*;
public class AudioClip2 {
public static void main(String[] args) throws
MalformedURLException, InterruptedException {
// Handling errors
String filnamn = JOptionPane.showInputDialog("Audio clip?");
// This is where I write what clip I wanna play
URL u = new URL(filnamn);
// Create a URL for my clip
AudioClip a = Applet.newAudioClip(u);
a.loop();
//Looping AudioClip a
Thread.sleep(10000); //Create a paus (ignore)
}
}

Related

Why does attempting to get a Clip throw exception?

I have been following this tutorial for Java 1.7 and I am sure I have the code right. However, Java throws an IllegalArgumentException at runtime.
I've tried to catch it in an existing catch block, using Java's slightly-newer multi-catch. However, it simply throws exceptions.
Here is the beginning of my code.
Mixer.Info[] mixInfos = AudioSystem.getMixerInfo();
/*
for (Mixer.Info info : mixInfos)
{
System.out.println(info.getName() + " - " + info.getDescription());
}
*/
mixer = AudioSystem.getMixer(mixInfos[0]);
DataLine.Info dataInfo = new DataLine.Info(Clip.class, null);
try
{
clip = (Clip) mixer.getLine(dataInfo);
}
I expect that the code will continue running and play the Clip but I get this exception:
Exception in thread "main" java.lang.IllegalArgumentException: Line unsupported: interface Clip
at java.desktop/com.sun.media.sound.PortMixer.getLine(PortMixer.java:131)
at main.Driver.main(Driver.java:35)
Note: If this isn't forward compatible, please explain.
I think you should check your imports. AFAIK, the libraries for sound are all in javax.sound.sampled. The PortMixer is in com.sun.media.sound.
The author of the tutorial is going to a lot more trouble than is necessary. Instead of hardcoding a specific Mixer, you can just let the system pick defaults. This is probably the best strategy, as PC's out in the world are going to have diverse hardware configurations.
Following is an example that might be helpful. Notice that we don't even bother to declare a Mixer.
import java.io.IOException;
import java.net.URL;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class BasicClipExample {
public static void main(String[] args) {
BasicClipExample bc = new BasicClipExample();
try {
bc.run();
} catch (UnsupportedAudioFileException | IOException
| LineUnavailableException | InterruptedException e) {
e.printStackTrace();
}
}
private void run() throws UnsupportedAudioFileException,
IOException, LineUnavailableException, InterruptedException
{
String filename = "a3.wav";
URL url = this.getClass().getResource("audio/" + filename);
System.out.println(url);
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
DataLine.Info info = new DataLine.Info(Clip.class, ais.getFormat());
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(ais);
clip.start();
Thread.sleep(6000);
clip.close();
}
}
This example assumes that your audio file is in a subdirectory called "/audio".
It also has a sleep command to keep the program running while the Clip is playing. Clips run under their own thread, but the thread is a "daemon" type and will not prevent a Java program from closing. My a3.wav is a recording of a bell that happens to last about 5 seconds.
Last thing, the above code does not use a Clip in the ideal fashion. The concept of a Clip is that it is for re-use. Reloading the clip variable before playing it each time it is played is inefficient. The clip variable should be loaded only once, and then played on demand. If you have clip.open() and clip.start() as contiguous lines of code, you should probably either be using a SourceDataLine instead of a Clip, or you should recode and put the two commands into separate methods.

Play audio files in Java

I am trying to play a simple audio file which is in the same directory near the class file. I tried many examples from the internet, but all the others gave me errors which I couldn't even understand.
Then I found this, and I am using it now.
There are neither compile errors nor runtime errors. But the problem is I cannot hear any noise.
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
class A{
public static void main (String[]args){
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("abc.wav").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch(Exception ex) {
System.out.println("Error with playing sound.");
}
}
}
Please note that my system volume is 80%, and the audio file plays in VLC media player.
Starting the audio clip does not block the main method. So
clip.start();
starts playing and then returns. Now your main method ends and therefore the Java process ends. No sound.
If you do
clip.start();
Thread.sleep(20000);
you should hear the clip playing for 20 seconds.
So for a working program just must make sure that the main thread does not end as long as you want to play the clip.
Hold the thread for a while until the audio clip plays.
long audioPlayTime = 1000; //clip duration in miliseconds.
try {
Thread.sleep(audioPlayTime);
} catch (InterruptedException ex){
//TODO
}

How to play .wav files in Java (looped)?

I've been rampaging about for a couple of hours now looking for sample code that can play simple wav files in Java. However, none of the ones I've received are working for me. Maybe it's just me that doesn't understand how to operate the sample code but could anyone provide me with sample code and "instructions" on how to get it working correctly. Any help would be much appreciated.
This code will create a clip and play it continuously once started:
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new URL(filename)));
clip.start();
clip.loop(Clip.LOOP_CONTINUOUSLY);
There are more modern ways to do this, but the applet class AudioClip might satisfy your needs:
import java.applet.Applet;
import java.applet.AudioClip;
final AudioClip clip = Applet.newAudioClip(resourceUrl);
To play it once:
clip.play();
To loop:
clip.loop();
clip.stop();
See Javadocs for Applet and AudioClip
getAudioClip
public AudioClip getAudioClip(URL url)
Returns the AudioClip object specified by the URL argument.
This method always returns immediately, whether or not the audio clip exists. When this applet attempts to play the audio clip, the data will be loaded.
Parameters:
url - an absolute URL giving the location of the audio clip.
Returns:
the audio clip at the specified URL.
You don't need to actually be doing anything with applets for this to work. It will work fine in a regular Java application.
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);
}
}

Error getting audio input stream from input URL

I am trying to play a .WAV in Java using the code from the javasound.info:
import java.net.URL;
import javax.swing.*;
import javax.sound.sampled.*;
public class LoopSound {
public static void main(String[] args) throws Exception {
URL url = new URL(
http://www.mediafire.com/listen/vgtpaigmj3un9ii/Untitled34.wav");
Clip clip = AudioSystem.getClip();
// getAudioInputStream() also accepts a File or InputStream
AudioInputStream ais = AudioSystem.
getAudioInputStream( url );
clip.open(ais);
clip.loop(Clip.LOOP_CONTINUOUSLY);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// A GUI element to prevent the Clip's daemon Thread
// from terminating at the end of the main()
JOptionPane.showMessageDialog(null, "Close to exit!");
}
});
}
}
But I am getting the following error:
Exception in thread "main" javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input URL
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1153)
at LoopSound.main(Wanderando.java:13)
I assume that the problem is with the URL itself and not the code, but I cannot for the life of me come across a service to upload and stream a .WAV file so that the program can capture the audio like in the original code with the :
http://pscode.org/media/leftright.wav
I am not sure if the code would have to be tweaked a bit for the to support mediafire's player or if there is another service for upload that support this.
Any help would be very appreciated.

How to play an mp3 file in java

I am trying to play a song (mp3 file) in java. I have been looking around for a few hours now and none of the ways I found worked properly.
public void play()
{
String song = "song.mp3";
Media track = new Media(song);
MediaPlayer mediaPlayer = new MediaPlayer(track);
mediaPlayer.play();
}
I have tried doing that but it gives me errors.
I have imported JMF and JLayer.
I have also read other questions that are like this one on this forum and none of them have helped me.
I just need a hand to help play an mp3 file.
The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29
Here is the code for the class
public class SimplePlayer {
public SimplePlayer(){
try{
FileInputStream fis = new FileInputStream("File location.");
Player playMP3 = new Player(fis);
playMP3.play();
}catch(Exception e){System.out.println(e);}
}
}
and here are the imports
import javazoom.jl.player.*;
import java.io.FileInputStream;
For this you'll need to install Java Media Framework (JMF) in your PC. One you have it installed,then try this piece of code:
import javax.media.*;
import java.net.*;
import java.io.*;
import java.util.*;
class AudioPlay
{
public static void main(String args[]) throws Exception
{
// Take the path of the audio file from command line
File f=new File("song.mp3");
// Create a Player object that realizes the audio
final Player p=Manager.createRealizedPlayer(f.toURI().toURL());
// Start the music
p.start();
// Create a Scanner object for taking input from cmd
Scanner s=new Scanner(System.in);
// Read a line and store it in st
String st=s.nextLine();
// If user types 's', stop the audio
if(st.equals("s"))
{
p.stop();
}
}
}
You may run into unable to handle formaterror, that is because Java took out the MP3 support by default (pirate copyright issue), you are required to install a “JMF MP3 plugin” in order to play MP3 file.
Go Java’s JMF website to download it
http://java.sun.com/javase/technologies/desktop/media/jmf/mp3/download.html
To be sure that you are using a supported format file, check here:
http://www.oracle.com/technetwork/java/javase/formats-138492.html
If you are using windows7, you may have to read this as well:
https://forums.oracle.com/forums/thread.jspa?threadID=2132405&tstart=45
How about JavaFX application-
import java.net.URL;
import javafx.application.Application;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
public class VLC extends Application {
void playMedia() {
String mp3 = "00- Tu Hi Mera.mp3";
URL resource = getClass().getResource(mp3);
System.out.println(resource.toString());
Media media = new Media(resource.toString());
MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
}
public static void main(String args[]) {
new VLC().playMedia();
}
#Override
public void start(Stage stage) throws Exception {
}
}

Categories