Java wav sounds NullPointer - java

I found this code on the Internet for playing a .wav file
public static synchronized void playSound(final String url) {
new Thread(new Runnable() {
public void run() {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(
ClientMain.class.getResourceAsStream("sounds/" + url));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
When I call getAudioInputStream() it gives me a NullPointerException.
Here is the error:
java.lang.NullPointerException
at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(SoftMidiAudioFileReader.java:130)
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1111)
at it.whispers.rain.ClientMain$10.run(ClientMain.java:415)
at java.lang.Thread.run(Thread.java:744)
java.net.SocketException: Socket is closed
at java.net.Socket.getOutputStream(Socket.java:916)
at it.whispers.rain.ClientMain.send(ClientMain.java:400)
at it.whispers.rain.ClientMain.Disconnect(ClientMain.java:373)
at it.whispers.rain.ClientMain.run(ClientMain.java:319)
at java.lang.Thread.run(Thread.java:744)
EDIT:
This is what i give when the .wav file is loaded:
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 it.whispers.rain.ClientMain$10.run(ClientMain.java:418)
at java.lang.Thread.run(Thread.java:744)

When you generate a .jar, you can embed resource files (files that can be read out by the java runtime environment).
This line reads out files that are embedded in the .jar:
ClientMain.class.getResourceAsStream("sounds/" + url));
Since you probably haven't added a .wav file in the sounds directory of the .jar file. The method cannot fetch that file and returns null. The file is (in most cases) loaded relatively from the class file (thus ClientMain.class).
You can simply modify the line by opening a File from the file system, or embed a wave file.
See this for more details.
EDIT: A second error is the format error. Perhaps you can solve this by fetching the format:
AudioFormat format = inputStream.getFormat();
and then:
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip clip = (Clip)AudioSystem.getLine(info);//you should postpone the creation of the clip
So the full code (in the Thread):
AudioInputStream inputStream = AudioSystem.getAudioInputStream(ClientMain.class.getResourceAsStream("sounds/" + url));
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip clip = (Clip)AudioSystem.getLine(info);
clip.open(inputStream);
clip.start();
Possibly you created a Clip that has an encoding/bitrate/... that does not correspond to the actual .wav file.

Related

How to append multiple files to Audio InputStream

I have an audio player, I have found how to add a single file to the audio inputstream, but I have an arraylist of files I want to add. How should I do that?
public class AudioPlayer {
Long currentFrame;
Clip clip;
// current status of clip
String status;
AudioInputStream musicInputStream;
// constructor to initialize streams and clip
public AudioPlayer(Schedule schedule,List<File> files)
throws UnsupportedAudioFileException,
IOException, LineUnavailableException
{
// create AudioInputStream object
musicInputStream =
AudioSystem.getAudioInputStream(files.get(0).getAbsoluteFile());
// create clip reference
clip = AudioSystem.getClip();
// open audioInputStream to the clip
clip.open(musicInputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
}
I'm sure this answer comes too late to be helpful to you, but I am searching for the answer to a similar question. The solution provided here suggests that you could create a loop to join two AudioInputStream objects together until you have a single final AudioInputStream:
Join two WAV files from Java?

JAVA - iterate through a folder of audio files, concatenating another audio file to each one

I am working on a small Java script to iterate through the .wav files in a folder named 'audiofiles', and concatenate each one individually with another audio file (named "silence_2sec.wav" in this case) So far I have:-
import java.io.File;
import java.util.*;
import java.io.*;
import javax.sound.sampled.*;
public class silapp_2b{
public static void main(String[]args){
String wavFile2 = "silence_2sec.wav";
// get list of file names from audio directory
File audDir = new File("audiofiles");
//define a list to contain the audio files names and path
File[] filesList = audDir.listFiles();
// assign contents of each wav file from filesList to a string
try {
for(File f : filesList){
if(f.isFile()){
AudioInputStream clip1 = AudioSystem.getAudioInputStream(new File(f.getName()));
AudioInputStream clip2 = AudioSystem.getAudioInputStream(new File(wavFile2));
AudioInputStream appendedFiles =
new AudioInputStream(
new SequenceInputStream(clip1, clip2),
clip1.getFormat(),
clip1.getFrameLength() + clip2.getFrameLength());
AudioSystem.write(appendedFiles,
AudioFileFormat.Type.WAVE,
new File("output" + "(f.getName()).wav"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This compiles, but returns the following error on execution:-
java.io.FileNotFoundException: glitch2.wav (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at com.sun.media.sound.WaveFloatFileReader.getAudioInputStream(WaveFloatFileReader.java:164)
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1181)
at silapp_2b.main(silapp_2b.java:32)
Any suggestions?
The error
AudioInputStream clip1 = AudioSystem.getAudioInputStream(new File(f.getName()));
This tries to create a file with the given file name, and looks for it in the current directory.
You should be using File.getAbsolutePath() to get the full absolute path to the file
AudioInputStream clip1 = AudioSystem.getAudioInputStream(new File(f.getAbsolutePath()));
or more simply
AudioInputStream clip1 = AudioSystem.getAudioInputStream(f);
Same problem with wavFile2
I suspect you will have the same issue with the second file:
AudioInputStream clip2 = AudioSystem.getAudioInputStream(new File(wavFile2));
You will need to provide an absolute path here too. If it also is in the audDir then do
File wavFile2 = new File(audDir.getAbsolutePath() + "/silence_2sec.wav");
AudioInputStream clip2 = AudioSystem.getAudioInputStream(wavFile2);

How to remove LOOP_CONTINUOUSLY in Javasound? [code inside]

I have saw this code somewhere in this area. I want to play the .wav file once but not continuously. How can I do that? I try removing the LOOP_CONTINUOUSLY line but it does not work.
URL url = new URL("http://pscode.org/media/leftright.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() {
JOptionPane.showMessageDialog(null, "Close to exit!");
}
});
And if possible. Can I play mp3 files as well. Because when I try to replace it as mp3, my code crashes. Also, I want to get the file from my computer. Not on the internet. Can anyone help me?
Use clip.start() instead of clip.loop(Clip.LOOP_CONTINUOUSLY)
Use File or getResourceAsStream() instead of URL and feed it to getAudioInputStream the same way
See this question for mp3 files

Java: Playing sound when message revived (IP chat program)

I know there are a lot of playing sound things. I am building a IP chat program. I am very new to programming (a nursing major if you must know). I am using eclipse. I am trying to have it play a sound when a message is received. I don't know how to make a class that will call the file and then play it. Thanks!
This is what i have right now (yes I know it is commented out):
public void playsound(final String input) {
final java.util.Date date= new java.util.Date();
//String stringFile = "x.wav";
//File wavfile = new File("notification.wav");
//AudioInputStream audioInput = AudioSystem.getAudioInputStream(wavfile);
//AudioFormat format = audioInput.getFormat();
//DataLine.Info info = new DataLine.Info(Clip.class, format);
//clip = AudioSystem.getClip();
}
Replacing clip = AudioSystem.getClip(); with
Clip clip = AudioSystem.getClip();
clip.open(audioInput);
clip.start();
removing String stringFile = "x.wav";
and uncommenting the rest should be sufficient.
There's a tutorial on playing files from a file inside a JAR here, which might be more useful than specifying a file in the file system: http://www3.ntu.edu.sg/home/ehchua/programming/java/J8c_PlayingSound.html

LineUnavailableException for playing mp3 with java

My goal is to play an mp3 file from Java. With every approach that I took, it always fails with a LineUnavailableException.
AudioInputStream inputStream = AudioSystem.getAudioInputStream(new URL("http://localhost:8080/agriserver/facebook/sound/test6.mp3"));
Clip clip = AudioSystem.getClip(info);
clip.open(inputStream);
clip.start();
Failed attempts to fix it:
Use Sun's mp3 plugin.
Use Jlayer 3rd party library
Use Tritonus 3rd party library
Re-encode the mp3 with Sony Sound Forge, Adobe Sound Booth, all no luck
Re-encode the mp3 with different encode rates and sampling rates
Try to use JMF
Use random mp3 from the Internet that plays fine in other applications
Read postings with the same error. None of the postings have an answer that helped resolve the issue.
Here is the exception:
Exception in thread "main" javax.sound.sampled.LineUnavailableException: line with format MPEG1L3 48000.0 Hz, unknown bits per sample, stereo, unknown frame size, 41.666668 frames/second, not supported.
at com.sun.media.sound.DirectAudioDevice$DirectDL.implOpen(DirectAudioDevice.java:494)
at com.sun.media.sound.DirectAudioDevice$DirectClip.implOpen(DirectAudioDevice.java:1280)
at com.sun.media.sound.AbstractDataLine.open(AbstractDataLine.java:107)
at com.sun.media.sound.DirectAudioDevice$DirectClip.open(DirectAudioDevice.java:1061)
at com.sun.media.sound.DirectAudioDevice$DirectClip.open(DirectAudioDevice.java:1151)
at Demo.playMp3(Demo.java:83)
Apparently, the mp3 has to be read into one stream. That stream has to be read into a second stream to decode it. The below code worked:
// read the file
AudioInputStream rawInput = AudioSystem.getAudioInputStream(new ByteArrayInputStream(data));
// decode mp3
AudioFormat baseFormat = rawInput.getFormat();
AudioFormat decodedFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED, // Encoding to use
baseFormat.getSampleRate(), // sample rate (same as base format)
16, // sample size in bits (thx to Javazoom)
baseFormat.getChannels(), // # of Channels
baseFormat.getChannels()*2, // Frame Size
baseFormat.getSampleRate(), // Frame Rate
false // Big Endian
);
AudioInputStream decodedInput = AudioSystem.getAudioInputStream(decodedFormat, rawInput);
OK - Let's start by ruling out your MP3 files and your code.
Pick an MP3 file that you have and
play it with any MP3 player.
Download
http://www.javazoom.net/javalayer/sources/jlayer1.0.1.zip
Extract jl1.0.1.jar from zip file
and put in your classpath
Cut and Paste the code at the end of this answer into your dev environment.
compile and run making sure your mp3
file in step 1 is the parameter to
the file. (In my case I had this "C:\\Users\\romain\\Music\\Al DiMeola\\Elegant Gypsy\\01 Flight over Rio Al DiMeola.mp3")
I tested this and it works fine.
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import javazoom.jl.player.Player;
public class MP3 {
private String filename;
private Player player;
// constructor that takes the name of an MP3 file
public MP3(String filename) {
this.filename = filename;
}
public void close() { if (player != null) player.close(); }
// play the MP3 file to the sound card
public void play() {
try {
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);
player = new Player(bis);
}
catch (Exception e) {
System.out.println("Problem playing file " + filename);
System.out.println(e);
}
// run in new thread to play in background
new Thread() {
public void run() {
try { player.play(); }
catch (Exception e) { System.out.println(e); }
}
}.start();
}
// test client
public static void main(String[] args) {
String filename = args[0];
MP3 mp3 = new MP3(filename);
mp3.play();
}
}

Categories

Resources