Pergunta

I'm trying to create a metronome for Android, and I wrote this code to play a beep at 300BPM using a SoundPool, but it tends to skip beats sometimes and creates lag. I have researched, and all of the answers I have found don't solve my issue. This especially happens when I try to speed up the bpm count or use eighth notes instead of quarter (double time). Can someone guide me in the right direction of making this as accurate as possible? Delay/beat-skipping is not acceptible. Thanks!!

     final SoundPool sndPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
     final int sndHigh = sndPool.load(this, R.raw.high, 1);
     setVolumeControlStream(AudioManager.STREAM_MUSIC);
     Thread th = new Thread(new Runnable(){
          public void run() {
            while(true){
                sndPool.play(sndHigh, 1f, 1f, 1, 0, 1f);
                //Log.d("asd", "beep");
                LockSupport.parkNanos(((240000/300)/4)*1000000); //300bpm
            }
          }
     });
     th.setPriority(Thread.MAX_PRIORITY);
     th.start();
Foi útil?

Solução

The solution is not to use a timer or SoundPool at all. Instead use a low-level AudioTrack that you manage continuously. You will have to synthesize the beep or click or whatever by inserting the appropriate samples into the AudioTrack at the proper point in the buffer. Just Google AudioTrack and look for samples on how it is used.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top