I'm writing an app to create a sound with depth to 32-bit audio, but can not understand much. I have a code that generates the tone and another that generates the audiotrack. I'm new in this topic, and I have not found what I ask from anywhere, so I open this question.
This generates a 16 bit tone with a sinusoidal equation:
void genTone(int numSamples,double sample[],int sampleRate,double freqOfTone,byte generatedSnd[]){
double x = 0
for (int i = 0; i < numSamples; ++i) {
x = i / (sampleRate / freqOfTone);
sample[i] = Math.sin(2 * Math.PI * x);
}
//scaling to the maximum amplitude
int idx = 0;
long val = 0;
for (final double dVal : sample) {
val = (long) ((dVal * 32767));
generatedSnd[idx++] = (byte) (val & 0x00ff);
generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8);
}
}
And this is the function that generates the audio track at 16bit:
void playSound(int sampleRate, byte generatedSnd[]){
final AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
sampleRate, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, generatedSnd.length,
AudioTrack.MODE_STATIC);
audioTrack.write(generatedSnd, 0, generatedSnd.length);
audioTrack.play();
Logically, I rewrote the code in this manner, but the sound output is rather strange. What's wrong?
Part of genTone function:
//changed byte generatedSnd to float generatedSnd32
void genTone(int numSamples,double sample[],int sampleRate,double freqOfTone,float generatedSnd32[]){
int idx = 0;
long val = 0;
for (final double dVal : sample) {
val = (long) ((dVal * 2147483647));
generatedSnd32[idx++] = (byte) (val & 0x00ff);
generatedSnd32[idx++] = (byte) ((val & 0xff00) >>> 8);
}
}
And this is the part of the function PlaySound at 32 bit:
void playSound(int sampleRate,float generatedSnd32[]){
final AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
sampleRate, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_FLOAT, generatedSnd.length,
AudioTrack.MODE_STATIC);
audioTrack.write(generatedSnd32, 0, generatedSnd.length,AudioTrack.WRITE_BLOCKING);
audioTrack.play();
}