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

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

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 wav sounds NullPointer

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.

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 - Trouble combining more than 2 .wav files

for a project I'm working on, I want to be able to concatenate multiple .wav files.
Through my research I was able to come up with this code:
File sample1 = new File("F:\\Programming\\Resources\\Java_Sound\\trumpet1.wav");
File sample2 = new File("F:\\Programming\\Resources\\Java_Sound\\trumpet2.wav");
File fileOut = new File("F:\\Programming\\Resources\\Java_Sound\\Test.wav");
AudioInputStream audio1 = AudioSystem.getAudioInputStream(sample1);
AudioInputStream audio2 = AudioSystem.getAudioInputStream(sample2);
AudioInputStream audioBuild = new AudioInputStream(new SequenceInputStream(audio1, audio2), audio1.getFormat(), audio1.getFrameLength() + audio2.getFrameLength());
//for(int i = 0; i < 5; i++){
// audioBuild = new AudioInputStream(new SequenceInputStream(audioBuild, audio2), audioBuild.getFormat(), audioBuild.getFrameLength() + audio2.getFrameLength());
//}
AudioSystem.write(audioBuild, AudioFileFormat.Type.WAVE, fileOut);
it works fine for combining two .wav files, however when I uncomment the for loop the produced .wav file only plays audio for the first concatenation. The audio track appears to end early, as wmp's duration bar only goes about 1\5 of the way across the screen.
I've assumed that the problem is with the header in the created .wav file. I've researched many different web pages discussing how a header in constructed, but all of them had slightly different definitions, but all said the header should be in hex. When converting the stream (not the audio stream, a standard FileInputStream) the headers I had were in decimal. Additionally, after the RIFF part, and before the WAVE part, is supposed to be the size of the whole file, not including the first 8 bytes. However some of mine included hyphens. To be honest I have no clue what those mean. Ignoring them however, the size of the test file after uncommenting the code above is still a larger number.
So after researching both how to concatenate multiple audio files, and how to create\manage .wav headers, I still have no clue why the rest of my audio isn't playing, if it even exists. Any help is greatly appreciated. Thanks in advance.
It might be because the input streams cannot be read more than once. Once you read an input stream, it will be at its end and attempt to read further will read no more bytes from that stream.
This should work with a slight modification, keep creating new audio input streams in your loop:
File sample1 = new File("f1.wav");
File sample2 = new File("f2.wav");
File fileOut = new File("combined.wav");
AudioInputStream audio1 = AudioSystem.getAudioInputStream(sample1);
AudioInputStream audio2 = AudioSystem.getAudioInputStream(sample2);
AudioInputStream audioBuild = new AudioInputStream(new SequenceInputStream(audio1, audio2), audio1.getFormat(), audio1.getFrameLength() + audio2.getFrameLength());
for(int i = 0; i < 5; i++)
{
audioBuild = new AudioInputStream(new SequenceInputStream(audioBuild, /* keep creating new input streams */ AudioSystem.getAudioInputStream(sample2)), audioBuild.getFormat(), audioBuild.getFrameLength() + audio2.getFrameLength());
}
AudioSystem.write(audioBuild, AudioFileFormat.Type.WAVE, fileOut);
Also, ensure your audio formats for the files are exactly the same. That is, same sample rate, same channel count, same bits per sample. Otherwise you'll need additional code to do sample conversion.
This is what I used to join any amount of wave files. I looped through a list of the string values for the wave file paths, and each time I join the previous resulting AudioInputStream with the next clip.
List<String> paths;
AudioInputStream clip1 = null;
for (String path : paths)
{
if(clip1 == null)
{
clip1 = AudioSystem.getAudioInputStream(new File(path));
continue;
}
AudioInputStream clip2 = AudioSystem.getAudioInputStream(new File(path));
AudioInputStream appendedFiles = new AudioInputStream(
new SequenceInputStream(clip1, clip2),
clip1.getFormat(),
clip1.getFrameLength() + clip2.getFrameLength());
clip1 = appendedFiles;
}
AudioSystem.write(clip1, AudioFileFormat.Type.WAVE, new File("exported.wav"));

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