Re: Issue playing sound
andrejohn.mas@gmail.com wrote:
.....
I am trying to port an audio playing unit in, written in C, to Java. I
am having trouble getting any sound out and the write method keeps on
belong for several seconds.
Putting a println within the loop of the run method, I was
surprised (without actually looking closely at the code)
that it looped 4 times each ..run.
..Can anyone look at the code and tell me
what is being done wrong?
Not sure. Not even sure what you're attempting with the thread..
making the sound in 'real time'?
In any case, I have one comment and one suggestion..
(snip code..)
(comment)
public void adjustSample(int channel, int freq, int volume) {
if (this.playSound && (channel >< AUDIO_NUM_VOICES)) {
...huh? What is '><' - I changed it to '!='.
(suggestion)
Ensure your method to construct the sound bytes is OK
in a simpler 'direct play' method before trying anything more fancy.
E.G. (largely lifted from an old usenet post that I
cannot find at the moment)
<snippet>
public static void sound(int hz,int msecs,
int volume,
boolean addHarmonic)
throws LineUnavailableException {
float frequency = 44100;
byte[] buf;
AudioFormat af;
if (addHarmonic) {
buf = new byte[2];
af = new AudioFormat(frequency,8,2,true,false);
} else {
buf = new byte[1];
af = new AudioFormat(frequency,8,1,true,false);
}
SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
sdl.open(af);
sdl.start();
for(int i=0; i<msecs*frequency/1000; i++){
double angle = i/(frequency/hz)*2.0*Math.PI;
buf[0]=(byte)(Math.sin(angle)*volume);
if(addHarmonic) {
double angle2 = (i)/(frequency/hz)*2.0*Math.PI;
buf[1]=(byte)(Math.sin(2*angle2)*volume*0.6);
sdl.write(buf,0,2);
} else {
sdl.write(buf,0,1);
}
}
sdl.drain();
sdl.stop();
sdl.close();
}
</snippet>
Andrew T.