Digital Sound & Music: Concepts, Applications, & Science, Chapter 2, last updated 6/25/2013
55
10
11 try {
12 ExampleTone1.createTone(262, 100);
13 } catch (LineUnavailableException lue) {
14 System.out.println(lue);
15 }
16 }
17
18 /** parameters are frequency in Hertz and volume
20 **/
21 public static void createTone(int Hertz, int volume)
22 throws LineUnavailableException {
23 /** Exception is thrown when line cannot be opened */
24
25 float rate = 44100;
26 byte[] buf;
27 AudioFormat audioF;
28
29 buf = new byte[1];
30 audioF = new AudioFormat(rate,8,1,true,false);
31 //sampleRate, sampleSizeInBits,channels,signed,bigEndian
32
33 SourceDataLine sourceDL = AudioSystem.getSourceDataLine(audioF);
34 sourceDL = AudioSystem.getSourceDataLine(audioF);
35 sourceDL.open(audioF);
36 sourceDL.start();
37
38 for(int i=0; irate; i++){
39 double angle = (i/rate)*Hertz*2.0*Math.PI;
40 buf[0]=(byte)(Math.sin(angle)*volume);
41 sourceDL.write(buf,0,1);
42 }
43
44 sourceDL.drain();
45 sourceDL.stop();
46 sourceDL.close();
47 }
48 }
Program 2.5 A simple sound generating program in Java
This program illustrates a simple of way of generating a sound by using a sine wave and the
javax.sound.sampled library. If we change the values of the createTone procedure parameters,
which are 262 Hz for frequency and 100 for volume, we can produce a different tone. The
second parameter, volume, is used to change the amplitude of the sound. Notice that the sine
function results is multiplied by the volume parameter in line 40.
Although the purpose of this section of the book is not to demonstrate how Java graphics
classes are used, it may be helpful to use some basic plot features in Java to generate sine wave
drawings. An advantage of Java is that it facilitates your control of windows and containers. We
inherit this functionality from the JPanel class, which is a container where we are going to paint
the sine wave generated. Program 2.6 is a variation of Program 2.5. It produces a Java Window
by using the procedure paintComponent. This sine wave generated again has a frequency of 262
Hz and a volume of 100.
Previous Page Next Page