How to easily create synth sounds in Android?

How to easily generate synthesizer sounds in Android? I want to be able to generate dynamically in a Music game using 8 bits. I tried with AudioTrack, but have not yet received good results of pleasant sounds.

Are there any examples?

I tried the following code without success:

public class BitLoose { private final int duration = 1; // seconds private final int sampleRate = 4200; private final int numSamples = duration * sampleRate; private final double sample[] = new double[numSamples]; final AudioTrack audioTrack; public BitLoose() { audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_8BIT, numSamples, AudioTrack.MODE_STREAM); audioTrack.play(); } public void addTone(final int freqOfTone) { // fill out the array for (int i = 0; i < numSamples; ++i) { sample[i] = Math.sin(2 * Math.PI * i / (sampleRate / freqOfTone)); } // convert to 16 bit pcm sound array // assumes the sample buffer is normalised. final byte generatedSnd[] = new byte[numSamples]; int idx = 0; for (final double dVal : sample) { // scale to maximum amplitude final short val = (short) ((((dVal * 255))) % 255); // in 16 bit wav PCM, first byte is the low order byte generatedSnd[idx++] = (byte) (val); } audioTrack.write(generatedSnd, 0, sampleRate); } public void stop() { audioTrack.stop(); } 
+7
source share
2 answers

I think the bad sound is due to the audio format: AudioFormat.ENCODING_PCM_8BIT uses unsigned samples, so the sine between 1 and -1 should be converted to 0-255 bytes, try the following:

 for (final double dVal : sample) { final short val = (short) ((dVal + 1) / 2 * 255) ; generatedSnd[idx++] = (byte) val; } 

Try also changing the sample rate to 11025, because the 4200 may not be supported on some devices:

 private final int sampleRate = 11025; 
+2
source

In addition to answer 1, you should use:
sample [i] = Math.sin (2 * Math.PI * i / ( (double) sampleRate / freqOfTone));
instead of sample [i] = Math.sin (2 * Math.PI * i / (sampleRate / freqOfTone));

0
source

All Articles