简体   繁体   中英

high resolution timer in android for metronome

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM