Java Sound .WAV format - java

I know this question has been asked a few times now about sound, and believe me, I have looked through to try and work out my own answer. I had the sound in Java working before on a different project without any difficulties using this:
public void playWelcome (){
try{
InputStream inputStream =
getClass().getResourceAsStream("Start.wav");
AudioStream audioStream = new AudioStream(inputStream);
AudioPlayer.player.start(audioStream);
}catch(IOException ioException){
ioException.printStackTrace();
System.out.println("Unable to Find WAV/Start FIle");
}
}
Obviously, this is not working before as explained so I have tried to use:
public void uploadDownload() {
try {
AudioInputStream audioInputStream =
AudioSystem.getAudioInputStream(new
File("/DaWord/src/resources/upload.wav").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch(Exception ex) {
System.out.println("Error with playing sound.");
ex.printStackTrace();
}
}
NOTE: I have tried the file without the slashes too. e.g. 'my file.wav'
Can someone help me out a bit here?
UPDATE:
So I have managed to get it going.. sort of:
File soundFile = new File("/Users/myname/DaWord/src/testing.wav");
AudioInputStream audioIn =
AudioSystem.getAudioInputStream(soundFile);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
But does anyone know how to do this by not providing the absolute path?? I have tried to use the .absoulutePath(); on the end of File such as : File
file = new File ("sound.wav").absouloutePath();

As explained here this are the ways to allocate a AudioInputStream piped from a file or URL,:
// from a wave File
File soundFile = new File("eatfood.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
// from a URL
URL url = new URL("http://www.zzz.com/eatfood.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
// can read from a disk file and also a file contained inside a JAR (used for distribution)
// recommended
URL url = this.getClass().getClassLoader().getResource("eatfood.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);

This worked for the time being... with full path
File soundFile = new File("/Users/mrBerns/NetBeansProjects/DaWord/src/ching.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();

Related

Playing custom audio formats with audio stream

So I started working on a video game and I want to create a custom sound format.
Path file = Paths.get("C:", "Users", "Mariobro85", "Desktop", "test.wav");
public void playFile() throws InterruptedException{
try{
File f = new File(file.toString());
URL url = f.toURI().toURL();
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(url);
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
Thread.sleep(15000);
}
catch(UnsupportedAudioFileException uafE){
System.out.println("ERROR: Audio data of the file " + file + " is not in wave format.");
}
catch(IOException ioE){
System.out.println("ERROR: Audio data of the file " + file + " is corrupted.");
}
catch(LineUnavailableException luE){
System.out.println(luE);
}
}
But this only plays standard .wav files.
I use wav in the custom format too, but the problem is that the audio data in my file starts at 0x60 instead of 0x0 and also there is information stored for loops, volume etc. Because of that it always throws an UnsupportedAudioFileException.
Is there any way to tell the AudioStream to jump to a specific address or is that not possible with standard java libraries?
If you want to edit the audio data before it is parsed by the default audio parser, you can edit it as follows
File file=new File("path/to/file");
byte[] bytes= Files.readAllBytes(file.toPath());
//edit or trim bytes as you wish.
ByteArrayInputStream inputStream=new ByteArrayInputStream(bytes);//you can even give an offset in this constructor
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(inputStream);
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
Thread.sleep(xAmount);
If your format is truly custom, I recommend just following one of these standardised approaches and simply adding a header or footer to your byte array. No need to remake what has been done. Or, to make things simpler, you can just add a separate file you also load which has different data you wish to load with the audio.

Playing .wav continuously in java: Invalid Format Exception

I want to play a .wav file continuously in Java. I found some code, but I can't make it work.
String fileName = "res/sound/buz.wav";
File file = new File(fileName);
AudioInputStream ais;
try {
Clip clip = AudioSystem.getClip();
ais = AudioSystem.getAudioInputStream(file);
clip.open(ais);
clip.loop(Clip.LOOP_CONTINUOUSLY);
} catch (UnsupportedAudioFileException | IOException
| LineUnavailableException e) {
e.printStackTrace();
}
I get an Invalid Format Exception on clip.open(ais):
Exception in thread "main" 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 launcher.Launcher.main(Launcher.java:59)
I checked and file is created correctly and exists. So, what is the problem with my code?
If it matters, I'm working on Linux, but this should work on both Linux and Windows...
So I found a solution
try{
File file = new File (fileName);
AudioClip clip = Applet.newAudioClip(file.toURL());
clip.loop();
clip.stop();
}
catch(Exception e){
e.printStackTrace();
}
I can play a .wav file in a loop and stop it. That's what I wanted. And the code is very short.

Java LWJGL OGG Background Music

In my game I've have got a very long ogg files(about 8 to 20 mb) and some other machines aren't able to read it direct into memory. So I read that some games uses stream and play method. Is there any lib/code example to load and play ogg files(with LWJGL) in real time?
Thanks for help :)
Do you specifically need to play OGG files? If not, there are plenty of online converters than can convert it to MP3, WAV, etc.
Also, do you specifically need to play it with LWJGL? This is very possible with default java, like so:
static String randomName = "TreasureQuest";
public static Clip clip = null;
public static void playSound(String name) throws Exception{
if (clip != null && clip.isOpen()) clip.close();
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("music/" + name + ".wav").getAbsoluteFile());
clip = AudioSystem.getClip();
clip.open(audioInputStream);
FloatControl gainControl =
(FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
gainControl.setValue(0f);
System.out.println(clip.getFrameLength() + " | " + clip.getFramePosition());
clip.start();
}
Personally, I use this for my LWJGL game, and it works perfectly fine.
If you must play an OGG file, and you specifically must play it with LWJGL, I suggest you use OpenAL. You can find the documentation for playing OGG files here.
#Joehot200
So I have two music engines - java clip and lwjgl, so it doesn't metter which one i will be using :)
I have a very similar code to yours(but it includes ogg decompression) and it time loading is still very long - I want to read my sound file and play what I read at the same time(like YOUTUBE). Here is my piece of code:
public static Clip DecodeOgg(String filename)
{
try
{
File file = new File(filename);
// Get AudioInputStream from given file.
AudioInputStream in= AudioSystem.getAudioInputStream(file);
AudioInputStream din = null;
if (in != null)
{
AudioFormat baseFormat = in.getFormat();
AudioFormat decodedFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(),
16,
baseFormat.getChannels(),
baseFormat.getChannels() * 2,
baseFormat.getSampleRate(),
false);
// Get AudioInputStream that will be decoded by underlying VorbisSPI
din = AudioSystem.getAudioInputStream(decodedFormat, in);
Clip clip = AudioSystem.getClip();
clip.open(din);
return clip;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}

Setting file path using Clip method. Java

I have been wondering how to change this method so i don't have to download the song from the internet, instead i want to play the song from a directory on my computer. Can somebody please give me an example of how i would do this?
URL url = new URL("myUrlToSong.wav"); //How I make this a directory?
//I get an error if i change it to a string
Clip clip = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.getAudioInputStream(url); //error is here id I
//change url to a string
clip.open(ais);
clip.loop(Clip.LOOP_CONTINUOUSLY);
Use any ofAudioSystem.getAudioInputStream(File) or AudioSystem.getAudioInputStream(InputStream).
File f = new File("mySong.wav");
AudioInputStream ais = AudioSystem.getAudioInputStream(f);
Or
InpuStream is = new FileInputStream(new File("mySong.wav"));
AudioInputStream ais = AudioSystem.getAudioInputStream(is);

Gridworld- Can you add sound?

Just like the title. I'm wondering if it's possible to play a song in the background, and if so, how does the code go for that? I've googled endlessly to no avail. Any help would be appreciated.
Try using the Clip class:
http://docs.oracle.com/javase/7/docs/api/javax/sound/sampled/Clip.html
I've used this code for many projects, and it always works
try {
// Open an audio input stream.
URL url = this.getClass().getClassLoader().getResource("path/fileName");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
// Get a sound clip resource.
clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
}catch(Exception e){
System.out.println(e);
}

Categories