This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Understanding how this code works Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Understanding how this code works" Watch "Understanding how this code works" New topic
Author

Understanding how this code works

jorge Garcia
Greenhorn

Joined: Jan 09, 2008
Posts: 16
I built a class to play a sound wav file and I had some trouble getting it to work from a jar file.

I found this code online and it solved my problem but I just don't get what it's doing.

This is the: in= this.getClass().getResourceAsStream("/audio/Bell.wav");

I don't see what 'this.getClass() is doing exactly? 'in' is an InputStream object so is 'this.getClass()' getting an instance of the class vs. getting an object?

Here is the full class code:

import javax.sound.sampled.*;
import java.io.*;
import java.net.*;




public class SoundTest {

//variable declaration

AudioInputStream stream;
AudioFormat format;
Clip clip;
DataLine.Info info;
InputStream in;


public static void main(String[] args) {

SoundTest soundtest = new SoundTest();
soundtest.go();

}

public void go() {

try{
in= this.getClass().getResourceAsStream("/audio/Bell.wav");
}catch(Exception e) {}

try {
stream = AudioSystem.getAudioInputStream(in);
System.out.println("stream");
} catch (Exception e) {}


format = stream.getFormat();
System.out.println("format");
info = new DataLine.Info(Clip.class,format);

try{
clip = (Clip) AudioSystem.getLine(info);
clip.open(stream);
System.out.println("Start is next");
System.out.println(Thread.currentThread());
clip.start();
System.out.println("Line after Start");
System.out.println(Thread.currentThread());
Thread.sleep(10000);
System.out.println(Thread.currentThread());
System.out.println("Line after Thread-Sleep");
} catch (Exception a) {}

}//close go

}//close class
Bill Shirley
Ranch Hand

Joined: Nov 08, 2007
Posts: 457
this is a reference to the current object you are executing code within,

getClass() is the class object it is an instance of

MyClass.class.getResourceAsStream("..."); // just about the same


Bill Shirley - bshirley - frazerbilt.com
if (Posts < 30) you.read( JavaRanchFAQ);
jorge Garcia
Greenhorn

Joined: Jan 09, 2008
Posts: 16
Thanks, Bill. I got it now, the object is a class.
 
Consider Paul's rocket mass heater.
 
subject: Understanding how this code works
 
Similar Threads
Could setting ByteArrayInputStream as InputStream deteriorate sound quality?
JAR + Including Files
Clip.start() behaviour
Play a .wav file
Getting audio to play in the background of my GUI.