Digital Sound & Music: Concepts, Applications, & Science, Chapter 2, last updated 6/25/2013
56
1 import javax.sound.sampled.AudioFormat;
2 import javax.sound.sampled.AudioSystem;
3 import javax.sound.sampled.SourceDataLine;
4 import javax.sound.sampled.LineUnavailableException;
5
6 import java.awt.*;
7 import java.awt.geom.*;
8 import javax.swing.*;
9
10 public class ExampleTone2 extends JPanel{
11
12 static double[] sines;
13 static int vol;
14
15 public static void main(String[] args){
16
17 try {
18 ExampleTone2.createTone(262, 100);
19 } catch (LineUnavailableException lue) {
20 System.out.println(lue);
21 }
22
23 //Frame object for drawing
24 JFrame frame = new JFrame();
25 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
26 frame.add(new ExampleTone2());
27 frame.setSize(800,300);
28 frame.setLocation(200,200);
29 frame.setVisible(true);
30 }
31
32 public static void createTone(int Hertz, int volume)
33 throws LineUnavailableException {
34
35 float rate = 44100;
36 byte[] buf;
37 buf = new byte[1];
38 sines = new double[(int)rate];
39 vol=volume;
40
41 AudioFormat audioF;
42 audioF = new AudioFormat(rate,8,1,true,false);
43
44 SourceDataLine sourceDL = AudioSystem.getSourceDataLine(audioF);
45 sourceDL = AudioSystem.getSourceDataLine(audioF);
46 sourceDL.open(audioF);
47 sourceDL.start();
48
49 for(int i=0; irate; i++){
50 double angle = (i/rate)*Hertz*2.0*Math.PI;
51 buf[0]=(byte)(Math.sin(angle)*vol);
52 sourceDL.write(buf,0,1);
53
54 sines[i]=(double)(Math.sin(angle)*vol);
55 }
56
57 sourceDL.drain();
Previous Page Next Page