Generating noise colors in Java
I want to create a color noise generator using Java, which will be able to generate all the colors defined in this article: http://en.wikipedia.org/wiki/Colors_of_noise
>Starting with the simplest one, white noise, how will I generate noise so that it can play indefinitely? > From there, how can I modify my generator to generate any color?
I'm confused about how to generate the noise itself and how to generate it that I can output through the speaker
Any links or tips will be appreciated!
I also looked at another problem: Java generating sound
But I don't fully understand what happened in the code given in one of the comments It doesn't tell me what kind of noise the code will produce, so I don't know how to modify it to produce white noise
Solution
This is a program that generates white noise with pure Java It can be easily changed to produce noise of other colors
import javax.sound.sampled.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.nio.ByteBuffer;
import java.util.Random;
public class WhiteNoise extends JFrame {
private GeneratorThread generatorThread;
public static void main(String[] args) {
EventQueue.invokelater(new Runnable() {
public void run() {
try {
WhiteNoise frame = new WhiteNoise();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public WhiteNoise() {
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
generatorThread.exit();
System.exit(0);
}
});
setTitle("White Noise Generator");
setResizable(false);
setDefaultClo@R_419_2360@peration(JFrame.EXIT_ON_CLOSE);
setBounds(100,100,200,50);
setLocationRelativeTo(null);
getContentPane().setLayout(new BorderLayout(0,0));
generatorThread = new GeneratorThread();
generatorThread.start();
}
class GeneratorThread extends Thread {
final static public int SAMPLE_SIZE = 2;
final static public int PACKET_SIZE = 5000;
SourceDataLine line;
public boolean exitExecution = false;
public void run() {
try {
AudioFormat format = new AudioFormat(44100,16,1,true,true);
DataLine.Info info = new DataLine.Info(SourceDataLine.class,format,PACKET_SIZE * 2);
if (!AudioSystem.isLineSupported(info)) {
throw new LineUnavailableException();
}
line = (SourceDataLine)AudioSystem.getLine(info);
line.open(format);
line.start();
} catch (LineUnavailableException e) {
e.printStackTrace();
System.exit(-1);
}
ByteBuffer buffer = ByteBuffer.allocate(PACKET_SIZE);
Random random = new Random();
while (exitExecution == false) {
buffer.clear();
for (int i=0; i < PACKET_SIZE /SAMPLE_SIZE; i++) {
buffer.putShort((short) (random.nextGaussian() * Short.MAX_VALUE));
}
line.write(buffer.array(),buffer.position());
}
line.drain();
line.close();
}
public void exit() {
exitExecution =true;
}
}
}
