我想创建一个使用
Java的彩色噪声生成器,它将能够生成本文中定义的所有颜色:
http://en.wikipedia.org/wiki/Colors_of_noise
>从最简单的一个,白噪声开始,我将如何产生噪音,以便它可以无限播放?
>从那里,我如何修改我的生成器以生成任何颜色?
我对如何产生噪声本身感到困惑,并对如何生成我可以通过扬声器输出它感到困惑.
我还看了另一个问题:Java generating sound
但我不完全理解其中一条评论中给出的代码中发生了什么.它也没有告诉我该代码会产生什么样的噪音,所以我不知道如何修改它会产生白噪声.
解决方法
这是一个用纯Java生成白噪声的程序.它可以很容易地改变以产生其他颜色的噪音.
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); setDefaultCloSEOperation(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; } } }