Reputation: 2939
I am trying to convert a 16bit mono sound to stereo. The sound is stored as a byte array, so to my understanding that means I duplicate two bytes at a time.
Am I doing this right? The code I produced changes the frequency.
EDIT:
I am successfully generating a mono tone and storing it in byte [] generatedSnd
Playing the mono sound (working):
AudioTrack audioTrack = null; // Get audio track
try {
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
sampleRate, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, (int)numSamples*2,
AudioTrack.MODE_STATIC);
audioTrack.setStereoVolume(0f, 1f);
audioTrack.write(generatedSnd, 0, generatedSnd.length); // Load the track
audioTrack.play(); // Play the track
}
catch (Exception e){ }
Converting to stereo sound:
int monoByteArrayLength = generatedSnd.length;
byte [] stereoGeneratedSnd = new byte[monoByteArrayLength * 2];
stereoGeneratedSnd[0] = generatedSnd[0];
stereoGeneratedSnd[2] = generatedSnd[0];
for (int x=1; x<monoByteArrayLength; x+=2) {
stereoGeneratedSnd[x*2-1] = generatedSnd[x];
stereoGeneratedSnd[x*2+1] = generatedSnd[x];
if (x+1 < monoByteArrayLength) {
stereoGeneratedSnd[x*2] = generatedSnd[x+1];
stereoGeneratedSnd[x*2+2] = generatedSnd[x+1];
}
}
AudioTrack audioTrack = null; // Get audio track
try {
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
sampleRate, AudioFormat.CHANNEL_OUT_STEREO,
AudioFormat.ENCODING_PCM_16BIT, (int)numSamples*2,
AudioTrack.MODE_STATIC);
audioTrack.setStereoVolume(0f, 1f);
audioTrack.write(stereoGeneratedSnd, 0, stereoGeneratedSnd.length); // Load the track
audioTrack.play(); // Play the track
}
catch (Exception e){ }
What I am trying to do is play the sound out of only one channel
Upvotes: 2
Views: 4742
Reputation: 423
Is that intentional that you duplicate two bytes at a time ? The stereo mode in 16bit PCM Wave format takes :
DATA[ ] : [1st byte from Chanel 1], [1st byte from Chanel 2], [2nd byte from Chanel 1], [2nd byte from Chanel 2]...
So that if you want to convert mono to stereo, your array should be :
Mono : 0, 1, 2, 3 ...
Stereo : 0, 0, 1, 1, 2, 2, 3, 3 ...
and if you want only one channel
Stereo : 0, 0, 1, 0, 2, 0, 3, 0 ...
Upvotes: 5
Reputation: 58507
The output from your doubling algorithm is 0, 1, 2, 1, 2, 3, 4, 3, 4, 5, 0, 5
.
A simpler (and correct) way of doing the doubling would be:
for (int i = 0; i < monoByteArrayLength; i += 2) {
stereoGeneratedSnd[i*2+0] = generatedSnd[i];
stereoGeneratedSnd[i*2+1] = generatedSnd[i+1];
stereoGeneratedSnd[i*2+2] = generatedSnd[i];
stereoGeneratedSnd[i*2+3] = generatedSnd[i+1];
}
Output: 0, 1, 0, 1, 2, 3, 2, 3, 4, 5, 4, 5
Upvotes: 2