Java AudioClip - no sound, no error - java

I've read prior issues about java AudioClip and have done my research, yet I still cannot figure out why this
AudioClip does not play. The .wav clip plays fine in Eclipse IDE, it is also in the appropriate directory; if the file
is in the incorrect directory this code snippet throws an error message.
My professor asked that we play the audioClip using this format also, audioClip = Applet.newAudioClip(new File(filePath).toURI().toURL());
When executed the play method at the bottom does get invoked however NO SOUND!
Any help would be appreciated.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.net.MalformedURLException;
public class PlaySoundApplet extends Applet implements ActionListener
{
private static final long serialVersionUID = 1L;
Button play,stop;
AudioClip audioClip;
public void init()
{
play = new Button("Play");
add(play);
play.addActionListener(this);
stop = new Button("Stop");
add(stop);
stop.addActionListener(this);
try
{
String filePath = "." + File.separator + "audio" + File.separator + "island_music.wav";
File file = new File(filePath);
if (file.exists())
{
audioClip = Applet.newAudioClip(file.toURI().toURL());
}
else
{
throw new RuntimeException("Directory " + filePath + " does not exist"); //debugging
}
}
catch (MalformedURLException malformedURLException)
{
throw new RuntimeException("Malformed URL: " + malformedURLException); //debugging
}
}
public void actionPerformed(ActionEvent ae)
{
Button source = (Button)ae.getSource();
if (source.getLabel() == "Play")
{
audioClip.play();
System.out.println("Play was executed");
}
else if(source.getLabel() == "Stop")
{
audioClip.stop();
System.out.println("Stop was executed");
}
}
}

Try the code with the simple leftright.wav.
..the leftright.wav works!!
Most media formats (sound, image, video etc.) are what is known as 'container formats'. The encoding of the media might be in any number of types. Java reads some encodings, but not others.
So I am guessing I have to try a different type of .wav file?
If it is for an application resource, I'd tend to convert the current WAV to a type that is compatible with Java Sound.

Do you mean after you build your program and run it the sound doesn't play? You should either embed the wav file into your resource folder and use getResources() to find the file. Or the other option would be to scan your local directory to find the file object with a matching name and file extension.
Also you are throwing the Malformed URL exception so you wont get an error if the URL is wrong. You shouldn't throw it, use try {...} catch (MalformedURLException mex) { system.out.println(mex.getMessage()) } instead.

Related

How can I convert a xml file to a xml written with javascript file with java?

I have got two XML files from two different databases, but they has got the same infos. One of them has got VSReports and the other Jasperreports(JavaScript). I has to convert the XML file from VSReports into the Jasperreports. The only programming language I am allowed to use is java.
I am already stucked when I try to read in a xml file with my code.
import javax.swing.*;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class InputBox {
public static void main(String[] args) {
Pfad();
}
//opens JFileChooser
public static void Pfad() {
JFileChooser chooser = new JFileChooser();
int rueckgabeWert = chooser.showOpenDialog(null);
if (rueckgabeWert == JFileChooser.APPROVE_OPTION) {
System.out.println("Die zu öffnende Datei ist: "
+ chooser.getSelectedFile().getName());
}
Path path = Paths.get(chooser.getSelectedFile().getName());
String content = null;
try {
content = Files.readString(path, Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println the content of the file
System.out.println(content);
}
}
It works really fine with a txt file, but when I try a XML file it comes to a error:
java.nio.file.NoSuchFileException: 123.xml
at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:85)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
at java.base/sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:231)
at java.base/java.nio.file.Files.newByteChannel(Files.java:370)
at java.base/java.nio.file.Files.newByteChannel(Files.java:421)
at java.base/java.nio.file.Files.readAllBytes(Files.java:3205)
at java.base/java.nio.file.Files.readString(Files.java:3283)
at InputBox.Pfad(InputBox.java:26)
at InputBox.main(InputBox.java:10)
null
you are trying to open a file without giving it an absolute path, it will only work if the file is in the current working directory
Based on your description, it seems you didn't pass the full name of the xml file to your function.
So try
File f = chooser.getSelectedFile();
String path = f.getAbsolutePath + f.getName();
try {
content = Files.readString(path, Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
}
Hope this help.
As said, File#getName() loses the directory part of the path, so it will only find a file if it is in the current directory. To convert a File object to a Path, just use its toPath() method:
Path path = chooser.getSelectedFile().toPath();

Java executable .jar file does not play MP3 file from external resource

I have a Java project in Netbeans which includes a User interface. From the interface the user can play an MP3 file that is stored in a folder "data" within the projects working directory.
For playing the file I have a class that creates an MP3 player and makes use of the JLayer.jar.
import java.awt.Component;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.swing.JFileChooser;
import javazoom.jl.player.Player;
public class MP3Player {
private String filename;
private Player player;
// a default constructor
public MP3Player() {}
// Constructor takes a given file name
public MP3Player(String filename) {
this.filename = filename;
}
public void close() { if (player != null) player.close(); }
// play the JLayerMP3 file to the sound card
public void play() {
try {
InputStream fis = new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);
player = new Player(bis);
}
catch (Exception e) {
System.out.println("\n Problem in playing: " + filename);
System.out.println(e);
}
}
public void play(String mp3filename) {
try {
InputStream fis = new FileInputStream(mp3filename);
BufferedInputStream bis = new BufferedInputStream(fis);
player = new Player(bis);
}
catch (Exception e) {
System.out.println("Problem in playing: " + mp3filename);
System.out.println(e);
}
// creata a thread to play music in background
new Thread() {
public void run() {
try { player.play(); }
catch (Exception e) { System.out.println(e); }
}
}.start();
}
Within the UI class I have a play button with an action method within which I create an MP3 player object. I then pass the filepath to the MP3 Player
MP3Player mp3 = new MP3Player();
mp3.play("data/audio/" + filepath);
As long as I run this project in Netbeans, it works fine and the music plays.
But once I create a jar file it does not play the music.
I found some other posts about similar problems
For example: Loading an mp3 file with JLayer from inside the Jar
But contrary to them I don't want to include the MP3 files in the JAR. It should take the files from a local folder "data".
I place the "data" folder containing the mp3.files in the same directory as the jar file. So the filepath is exactly the same as when I have it in the Netbeans project's working directory and run it from Netbeans (as I said there is no problem then).
And the JAR gets all the other data like textfiles and images without any problems from the local "data" folder.
Any help is highly appreciated.
Netbeans creates dirctory like this: YourProjectDir/dist/YourProject.jar. Your libraries are placed inside YourProjectDir/dist/lib/otherlibrary.jar. Create your data folder inside your YourProjectDir i.e. your media files will remain inside YourProjectDir/data/audio/.
What you do, just create a batch file with any name.
#echo off
START/MAX dist\YourProject.jar
Place the Batch file inside YourProjectDir. Now run the Batch file.

How to play an mp3 file given an absolute file name?

I've found some would-be answers on Stack Overflow, but they are old and it looks like they use deprecated technologies.
I need to play an mp3 file given an absolute file name.
Here is what I've tried:
1. JavaFX
MediaPlayer player = new MediaPlayer(new Media(uriString));
I am getting java.lang.IllegalStateException: Toolkit not initialized.
I could probably find a way to initialize that toolkit, but I'd like to know if it's the preferred way.
2. Intellij UIUtil
final InputStream is = new FileInputStream(fileName);
UIUtil.playSoundFromStream(new Factory<InputStream>() {
#Override
public InputStream create() {
return is;
}
});
I am getting Audio format is not yet supported: could not get audio input stream from input file
I've made some more attempts, but this is what I have a record of.
The only thing that's working for me so far is playing files from shell: on Mac,
Runtime.getRuntime().exec("afplay " + filePath);
But I'd prefer a Java solution. Any ideas?
For JavaFX
You can have a look here Getting a mp3 file to play using javafx
Here you are,my favourite part:
You can use JLayer which supports .mp3.
Example
new Thread(()->{
try {
FileInputStream file = new FileInputStream("path ..../audio.mp3"); //initialize the FileInputStream
Player player= new Player(file); //initialize the player
player.play(); //start the player
} catch (Exception e) {
e.printStackTrace();
}
}).start();
Note:
Note that i am using a separate Thread cause if not the application will stack.
Generally Speaking:
You have to use external libraries to play files like .mp3 in Java(although JavaFX supports .mp3 but not all formats)
Java supports only .wav
Although that's enough.All you need is an external algorithm to play other music formats.All the other format's come originally from .wav,they pass into an algorithm and then boom they become .ogg,.mp3,.whatever
1.As mentioned before for .mp3 JLayer.jar
You can import this jar into your project as an external library.
2.JavaZoom has also and other libraries to support .ogg,.speex,.flac,.mp3,follow the link above and download the jlGui project there you can find libraries for a lot of formats.
Link to stackoverflow on
How to play .wav files with java
And http://alvinalexander.com/java/java-audio-example-java-au-play-sound
Not sure if that still works with java 8
Code:
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.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class AudioPlayerExample1 implements LineListener {
/**
* this flag indicates whether the playback completes or not.
*/
boolean playCompleted;
/**
* Play a given audio file.
* #param audioFilePath Path of the audio file.
*/
void play() {
File audioFile = new File("C:/Users/Alex.hp/Desktop/Musc/audio.wav");
try {
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip audioClip = (Clip) AudioSystem.getLine(info);
audioClip.addLineListener(this);
audioClip.open(audioStream);
audioClip.start();
while (!playCompleted) {
// wait for the playback completes
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
audioClip.close();
} catch (UnsupportedAudioFileException ex) {
System.out.println("The specified audio file is not supported.");
ex.printStackTrace();
} catch (LineUnavailableException ex) {
System.out.println("Audio line for playing back is unavailable.");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("Error playing the audio file.");
ex.printStackTrace();
}
}
/**
* Listens to the START and STOP events of the audio line.
*/
#Override
public void update(LineEvent event) {
LineEvent.Type type = event.getType();
if (type == LineEvent.Type.START) {
System.out.println("Playback started.");
} else if (type == LineEvent.Type.STOP) {
playCompleted = true;
System.out.println("Playback completed.");
}
}
public static void main(String[] args) {
AudioPlayerExample1 player = new AudioPlayerExample1();
player.play();
}
}

Cannot Figure Out Why Audio File Is Not Playing (Java)

Kind of a noob to coding, but I've been creating Pacman for a computer science class, and for some reason, I cannot get my audio to work.
Basically, here is the just of what I have written.
public void paint(Graphics g)
{
PlayAudio();
//.... a lot of other stuff
}
My PlayAudio method:
public void PlayAudio()
{
try
{
Clip clickClip = AudioSystem.getClip();
File filePath = new File("opening.wav");
AudioInputStream ais = AudioSystem.getAudioInputStream(filePath);
clickClip.open(ais);
clickClip.start();
}
catch (Exception e)
{
e.printStackTrace();
}
}
It compile and executes, but the audio file does not play. Thanks for the help!
I have confirmed that my opening.wav:
Is a .wav file.
Has the right name.
Is in the same directory.
Java 7 include new classes to play audio. Media and MediaPlayer. Example:
String media = "media.mp3";
Media hit = new Media(media);
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
you need this libreries :
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;

Java Applet to Download files files

I have an applet that is executed in an HTML file that the user downloads and opens locally (i.e. file:// on the URL bar). This applet has a method that downloads a file from the web and stores it in a directory inside the directory where the applet is running. On my HTML file I call the function to download a file and it works but when I call it the second time, to download another file, I get a Error calling method on NPObject. I don't get any error on the Java side (I have the console open and it stays clean).
What can be the issue here? Thank you a lot for your help. Below, the code of the applet.
import java.security.*;
import java.io.*;
import java.nio.channels.*;
import java.net.*;
public class EPPenDrive extends java.applet.Applet {
public final static String baseURL = "http://localhost/data/documents/";
public String downloadFile(final String filename) {
return (String)AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
URL finalURL = new URL(baseURL + filename);
ReadableByteChannel rbc = Channels.newChannel(finalURL.openStream());
URL appletDir = getCodeBase();
FileOutputStream fos = new FileOutputStream(appletDir.getPath() + "documents/"+ filename);
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
return 1;
} catch (Exception x) {
x.printStackTrace();
return null;
}
}
});
}
public void init() { }
public void stop() { }
}
I found the problem: the run() method would block if returning 1. I changed it to return null and now everything works. :)

Categories

Resources