Digital Sound & Music: Concepts, Applications, & Science, Chapter 2, last updated 6/25/2013
Figure 2.57 Sound waves generated in a Java program
We can also create square, triangle, and sawtooth waves in Java by modifying the for loop in
lines 38 to 42. For example, to create a square wave, we may change the for loop to something
like the following:
46 for(int i=0; irate; i++){
47 double angle1 = i/frequency*hz*1.0*2.0*Math.PI;
48 double angle2 = i/frequency*hz*3.0*2.0*Math.PI;
49 double angle3 = i/frequency*hz*5.0*2.0*Math.PI;
50 double angle4 = i/frequency*hz*7.0*2.0*Math.PI;
52 buf[0]=(byte)(Math.sin(angle1)*vol+
53 sdl.write(buf,0,1);
55 sines[i]=(double)(Math.sin(angle1)*vol+
57 }
This for loop produces the sine wave shown in Figure 2.58. This graph doesn't look like a perfect
square wave, but the more harmonic frequencies we add, the closer we get to a square wave.
(Note that you can create these waveforms more exactly by adapting the Octave programs above
to Java.)
Previous Page Next Page