high resolution timer in android for metronome

不打扰是莪最后的温柔 提交于 2020-06-27 18:36:30

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/14106786/high-resolution-timer-in-android-for-metronome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!