Durante l'esecuzione del codice riportato di seguito viene visualizzata una leggera distorsione (simile al ronzio). A causa della sua natura sottile, fa credere che ci sia una sorta di aliasing in corso con il byte casting.Rumore di fondo durante la generazione di onda sinusoidale in Java
Formato audio = PCM_SIGNED 44100,0 Hz, 16 bit, stereo, 4 byte/telaio, big-endian
Nota: codice presuppone (per ora) che i dati sono in grande endian.
public static void playFreq(AudioFormat audioFormat, double frequency, SourceDataLine sourceDataLine)
{
System.out.println(audioFormat);
double sampleRate = audioFormat.getSampleRate();
int sampleSizeInBytes = audioFormat.getSampleSizeInBits()/8;
int channels = audioFormat.getChannels();
byte audioBuffer[] = new byte[(int)Math.pow(2.0, 19.0) * channels * sampleSizeInBytes];
for (int i = 0; i < audioBuffer.length; i+=sampleSizeInBytes*channels)
{
int wave = (int) (127.0 * Math.sin(2.0 * Math.PI * frequency * i/(sampleRate * sampleSizeInBytes * channels)) );
//wave = (wave > 0 ? 127 : -127);
if (channels == 1)
{
if (sampleSizeInBytes == 1)
{
audioBuffer[i] = (byte) (wave);
}
else if (sampleSizeInBytes == 2)
{
audioBuffer[i] = (byte) (wave);
audioBuffer[i+1] = (byte)(wave >>> 8);
}
}
else if (channels == 2)
{
if (sampleSizeInBytes == 1)
{
audioBuffer[i] = (byte) (wave);
audioBuffer[i+1] = (byte) (wave);
}
else if (sampleSizeInBytes == 2)
{
audioBuffer[i] = (byte) (wave);
audioBuffer[i+1] = (byte)(wave >>> 8);
audioBuffer[i+2] = (byte) (wave);
audioBuffer[i+3] = (byte)(wave >>> 8);
}
}
}
sourceDataLine.write(audioBuffer, 0, audioBuffer.length);
}
Ah! Guarda l'errore ora, dopo aver corretto la parte di ampiezza l'errore è diventato molto evidente, ma anche il tuo codice è più efficiente. Grazie! – yxk
Analisi ben fatte! –