0

How to change the duration of the audiotrack by an infinite loop?

I understand that I must apply the following line before audioTrack.play():

audioTrack.setLoopPoints (0, generatedSnd.length, -1);

For example, I want the duration will be half a second, therefore, the "duration" variable of type "int" isn't valid. To do so I want the sound to play repeatedly and control the time to stop with a Timer.

The code is:

  private int duration = 1; // seconds
    private int sampleRate = 44100; 
    private final int numSamples = duration * sampleRate;
    private final double sample[] = new double[numSamples];
    private double freqOfTone = 261.626; // For example musical note C (Do) is 261.626Hz.
    private final byte generatedSnd[] = new byte[2 * numSamples];

final Thread thread = new Thread(new Runnable() {
                    public void run() {
                        genTone();
                        handler.post(new Runnable() {

                            public void run() {
                                playSound();
                            }
                        });
                    }
                });
                thread.start();
            }
        });


    void genTone() {        
        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.
        int idx = 0;
        for (final double dVal : sample) {
            // scale to maximum amplitude
            final short val = (short) ((dVal * 32767));
            // in 16 bit wav PCM, first byte is the low order byte
            generatedSnd[idx++] = (byte) (val & 0x00ff);
            generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8);

        }
    }

    void playSound(){
        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();
    }
ephramd
  • 561
  • 2
  • 15
  • 41

2 Answers2

0

I think audioTrack.write(generatedSnd, 0, generatedSnd.length); 0 equal all track u can but edittext then use : audioTrack.write(generatedSnd, edittext, generatedSnd.length); then when user tape 20 before click play >> the player will loop after 20 second

H4F
  • 131
  • 10
0

This one worked for me:

audioTrack.setLoopPoints(0, generatedSnd.length/FRAME_SIZE, -1);

if you are playing on 5.1 system then frame size if 12 (6*2), or for 7.1 it's 16 (8*2), for stereo it's 4.

user531069
  • 985
  • 8
  • 28