【发布时间】:2015-11-30 20:03:09
【问题描述】:
我正在尝试在 java 中运行一个创建符号波的对象。我需要在自身上运行这个对象。我决定使用线程来尝试实现这一点。当我运行它时,它给我一个错误,说“无法解决音调”,错误发生在我定义 t1 和 t2 的行上。我对线程非常陌生,对此的任何帮助将不胜感激。感谢您的宝贵时间和帮助!
代码:
package dreamBeats;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
public class dreamBeatsClass extends Thread{
static int length;
static int wavelength;
protected static final int SAMPLE_RATE = 16 * 1024;
//makes a sine wave buffer
public static byte[] createSinWaveBuffer(double freq, int ms) {
int samples = (int)((ms * SAMPLE_RATE) / 1000);
byte[] output = new byte[samples];
//
double period = (double)SAMPLE_RATE / freq;
for (int i = 0; i < output.length; i++) {
double angle = 2.0 * Math.PI * i / period;
output[i] = (byte)(Math.sin(angle) * 127f); }
return output;
}
// run the tone object
public void run(){
try {
tone(length, wavelength);
} catch (LineUnavailableException e) {}
}
//create the threads and run them during one another
public static void main(String[] args) throws LineUnavailableException, InterruptedException {
Thread t1 = new Thread (new tone(1000, 400));
Thread t2 = new Thread (new tone(1000, 500));
t1.start();
t2.start();
}
// create the sine wave
public static void tone(int time, int wave) throws LineUnavailableException{
final AudioFormat af = new AudioFormat(SAMPLE_RATE, 8, 1, true, true);
SourceDataLine line = AudioSystem.getSourceDataLine(af);
line.open(af, SAMPLE_RATE);
line.start();
boolean forwardNotBack = true;
for(double freq = wave; freq <= wave*2;) {
byte [] toneBuffer = createSinWaveBuffer(freq, time);
int count = line.write(toneBuffer, 0, toneBuffer.length);
if(forwardNotBack) {
freq += wave/4;
forwardNotBack = false; }
else {
forwardNotBack = true;
} }
line.drain();
line.close();
length = time;
wavelength = wave;
}
}
【问题讨论】:
-
Java 区分大小写。没有对象以小写字母开头。可能你会一个一个地改变音调......但我没有看到任何音调的导入。
标签: java multithreading oop