我寫了這個小信號生成方法。我的目標是在兩個通道(左和右)之間稍微有一段時間延遲或兩個通道之間的增益稍有差異時發出蜂鳴聲。 目前,我通過爲一個通道填充一個緩衝區來創建延遲,併爲第二個通道填充一個緩衝區值,並進一步減少通道之間的行爲(如果您有任何提示或想法如何更好地執行此操作,將不勝感激。) The下一階段正在做一些類似於增益的事情。我已經看到Java通過FloatControl給內置增益控制:單獨使用Java控制聲音通道的增益
FloatControl gainControl =
(FloatControl) sdl.getControl(FloatControl.Type.MASTER_GAIN);
但我不確定如何分別控制每個通道的增益。有沒有內置的方法來做到這一點? 我需要兩個獨立的流,每個通道一個流?如果是這樣,我該如何同時播放它們? 我對聲音編程頗爲陌生,如果有更好的方法來做到這一點,請讓我知道。很感謝任何形式的幫助。
這是我到目前爲止的代碼:
public static void generateTone(int delayR, int delayL, double gainRightDB, double gainLeftDB)
throws LineUnavailableException, IOException {
// in hz, number of samples in one second
int sampleRate = 100000; // let sample rate and frequency be the same
// how much to add to each side:
double gainLeft = 100;//Math.pow(10.0, gainLeftDB/20.0);
double gainRight = 100;// Math.pow(10.0, gainRightDB/20.0);;
// click duration = 40 us
double duration = 0.08;
double durationInSamples = Math.ceil(duration * sampleRate);
// single delay window duration = 225 us
double baseDelay = 0.000225;
double samplesPerDelay = Math.ceil(baseDelay * sampleRate);
AudioFormat af;
byte buf[] = new byte[sampleRate * 4]; // one second of audio in total
af = new AudioFormat(sampleRate, 16, 2, true, true); // 44100 Hz, 16 bit, 2 channels
SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
sdl.open(af);
sdl.start();
// only one should be delayed at a time
int delayRight = delayR;
int delayLeft = delayL;
int freq = 1000;
/*
* NOTE:
* The buffer holds data in groups of 4. Every 4 bytes represent a single sample. The first 2 bytes
* are for the left side, the other two are for the right. We take 2 each time because of a 16 bit rate.
*
*
*/
for(int i = 0; i < sampleRate * 4; i++){
double time = ((double)i/((double)sampleRate));
// Left side:
if (i >= delayLeft * samplesPerDelay * 4 // when the left side plays
&& i % 4 < 2 // access first two bytes in sample
&& i <= (delayLeft * 4 * samplesPerDelay)
+ (4 * durationInSamples)) // make sure to stop after your delay window
buf[i] = (byte) ((1+gainLeft) * Math.sin(2*Math.PI*(freq)*time)); // sound in left ear
//Right side:
else if (i >= delayRight * samplesPerDelay * 4 // time for right side
&& i % 4 >= 2 // use second 2 bytes
&& i <= (delayRight * 4 * samplesPerDelay)
+ (4 * durationInSamples)) // stop after your delay window
buf[i] = (byte) ((1+gainRight) * Math.sin(2*Math.PI*(freq)*time)); // sound in right ear
}
for (byte b : buf)
System.out.print(b + " ");
System.out.println();
sdl.write(buf,0,buf.length);
sdl.drain();
sdl.stop();
sdl.close();
}
*「..不知道如何分別控制每個通道的增益。」* ['FloatControl.Type.BALANCE'](http://docs.oracle.com/javase/8/docs/api/javax /sound/sampled/FloatControl.Type.html#BALANCE).. –
爲了儘快提供更好的幫助,請發佈[MCVE]或[簡短,獨立包含,正確示例](http://www.sscce.org/)。 –