Created
March 29, 2017 20:14
-
-
Save mpuz/78e9e875df646698243affe1870dda58 to your computer and use it in GitHub Desktop.
Android, Java: mix 2 PCM audio files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void mixSound() throws IOException { | |
AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT, 44100, AudioTrack.MODE_STREAM); | |
InputStream in1=getResources().openRawResource(R.raw.track1); | |
InputStream in2=getResources().openRawResource(R.raw.track2); | |
byte[] music1 = null; | |
music1= new byte[in1.available()]; | |
music1=convertStreamToByteArray(in1); | |
in1.close(); | |
byte[] music2 = null; | |
music2= new byte[in2.available()]; | |
music2=convertStreamToByteArray(in2); | |
in2.close(); | |
byte[] output = new byte[music1.length]; | |
audioTrack.play(); | |
for(int i=0; i < output.length; i++){ | |
float samplef1 = music1[i] / 128.0f; // 2^7=128 | |
float samplef2 = music2[i] / 128.0f; | |
float mixed = samplef1 + samplef2; | |
// reduce the volume a bit: | |
mixed *= 0.8; | |
// hard clipping | |
if (mixed > 1.0f) mixed = 1.0f; | |
if (mixed < -1.0f) mixed = -1.0f; | |
byte outputSample = (byte)(mixed * 128.0f); | |
output[i] = outputSample; | |
} //for loop | |
audioTrack.write(output, 0, output.length); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment