LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Java sound: line.write() returns 0 (http://www.linuxquestions.org/questions/programming-9/java-sound-line-write-returns-0-a-591970/)

eantoranz 10-15-2007 12:15 PM

Java sound: line.write() returns 0
 
I'm trying to play a sine wave.

I have a SourceDataLine, but when I try to write to it, the write method return 0, meaning that it coulen't write anything to the mixer's output stream, right? I also don't get to hear a thing, by the way.

Here's the code I'm using:
Code:

byte [] sample = new byte[4];
int written = 0;
while (true) {
        int valor = (int) ((2 << 15 -1) * wave.height());
        //System.out.println(valor);
        sample[0] = sample[2] = (byte) (valor & 0xff);
        sample[1] = sample[3] = (byte) (valor >> 8);
        written = line.write(sample, 0, 4);
        if (written != 4) {
                System.err.println("Couldn't write all the bytes!");
                System.exit(1);
        }
        line.drain();
        wave.tic();
}

wave.height() returns the height of the wave (-1 to 1) for that moment in time.

The Audio Format is PCM_SIGNED, at 44.1 KHtz, 16 bits per sample, Stereo, little endian.

Any ideas?

eantoranz 10-15-2007 10:13 PM

I will refrase the problem:

How can I get a SourceDataLine I could use to hear a wave? Im doing this, but I don't get a single line that works:

Code:

AudioFormat format = new AudioFormat(44100f, 16, 2, true, false);
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

SourceDataLine line = null;
Mixer.Info [] mixerInfo = AudioSystem.getMixerInfo();
Mixer mixer;
for (int i = 0; line == null && i < mixerInfo.length; i++) {
        mixer = AudioSystem.getMixer(mixerInfo[i]);
        try {
                line = (SourceDataLine) mixer.getLine(info);
                if (!line.getLineInfo().matches(info)) {
                        line = null;
                }
        } catch (LineUnavailableException e) {
                line = null;
        } catch (IllegalArgumentException e) {
                line = null;
        }
}
               
if (line == null) {
        System.out.println("No line was found");
        System.exit(1);
}

The funny thing is that sometimes mixer.getLine(info) does return a mixer, but then the matches(info) fails. How can I get that done?


All times are GMT -5. The time now is 04:06 AM.