2

How can I play a melody in android 5, let's say 440Hz, 480Hz, 500Hz, 440Hz? Other systems have sth. like "sound(440)". Or do I have to synthesize it with AudioTrack?

  • Can you add some more information with the code you are trying? – Stefan Feb 11 '17 at 10:55
  • 1
    Yes you should do it with `AudioTrack`: http://stackoverflow.com/questions/9106276/android-how-to-generate-a-frequency – zed Feb 11 '17 at 11:38

1 Answers1

1

Yes, you will have to synthesize it using AudioTrack as pointed out by @zed.

Here's some piece of code that should help you

 final static double scale = 1;
 final static int duration = 50; // Seconds
 final static int sampleRate = 22050; // Hz (maximum frequency is 7902.13Hz (B8))
 final static int numSamples = duration * sampleRate;
 final static double samples[] = new double[numSamples];
 final static short buffer[] = new short[numSamples];


double note = scale * frequency;
for (int i = 0; i < numSamples; ++i)
 {
      samples[i] = Math.sin(2 * Math.PI * i / (sampleRate / note)); // Sine wave
      buffer[i] = (short) (samples[i] * Short.MAX_VALUE);  // Higher amplitude increases volume
 }

audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,sampleRate,AudioFormat.CHANNEL_OUT_MONO,
                AudioFormat.ENCODING_PCM_16BIT, buffer.length,AudioTrack.MODE_STATIC);
audioTrack.write(buffer, 0, buffer.length);
Ayush Bansal
  • 702
  • 1
  • 7
  • 17