0

I researched Sine wave generating on Android for a long time and I got some sample code online. However, I still got in confusion when I code by myself. I use the code like following

double[] buf = new double[(int) sampleRate];
byte[] buffer = new byte[(int) sampleRate];
double sampleInterval = sampleRate/frequency;
for(int i=0; i<sampleRate;i++){
    buf[i] = (Math.sin((2.0*Math.PI*i)/sampleInterval));
    buffer[i] = (byte)(buf[i]*Byte.MAX_VALUE);
}
while(flag) {
    audioTrack.write(buffer, 0, buffer.length);
}
  1. I there is too much noise when I play the sine wave buffer generated by the formula "Math.sin((2.0*Math.PI*i)/sampleInterval)". I don't know it is the problem of Java & Android or my coding. Both on the simulator and my real Sony Phone showed the noise. But the same formula with Matlab on my classmate's laptop can work well. I have also tried to use DataSourceLine in desktop java code. The noise also exists.

2.The sound generated tend to be unstable, sometimes it is continuous, but sometimes it can be intermittent with obvious regular ups and downs in the sound.

How can I improve my code to makes it stable and accurate?

Ori.Lin
  • 421
  • 1
  • 5
  • 13
  • Possible duplicate of [Noise in background when generating sine wave in Java](http://stackoverflow.com/questions/740619/noise-in-background-when-generating-sine-wave-in-java) – Pete B. Apr 14 '16 at 15:00

1 Answers1

0

Why two buffers?

You could do it with one

double phase = 0.0;
amp = 10000;
short[] buffer = new short[BUFSIZE]; // BUFSIZE should be result from audiotrack.getMinBufferSize
double phaseIncrement = (2 * Math.PI * frequency) / sampleRate;
for (int i = 0; i < BUFSIZE; i++) {
    buffer[i] = (short) (amp * Math.sin(phase));
    phase += phaseIncrement;
}

audioTrack.write(buffer, 0, buffer.length);
Syntey
  • 147
  • 1
  • 15
  • I tried to update my code. It works and the noise reduced. But sometimes they still exist. For example, When I set the frequency as 21000, it may emit out a very shrill voice. Can it be the instability of Java? – Ori.Lin Apr 14 '16 at 14:32
  • Why would you need such a high frequency? – Syntey Apr 14 '16 at 15:18
  • That comes from my research project in my Uni. I need to generate a sound that people cannot hear. – Ori.Lin Apr 15 '16 at 01:34
  • Ok, if the device is fully capable of sounding this high frequencies, then I don't know. You could ask another question with this exact problem – Syntey Apr 15 '16 at 09:51