Skip to content

Instantly share code, notes, and snippets.

@syrm
Created November 26, 2018 13:10
Show Gist options
  • Save syrm/e29da998e0d3f1e96bd4b103536c9336 to your computer and use it in GitHub Desktop.
Save syrm/e29da998e0d3f1e96bd4b103536c9336 to your computer and use it in GitHub Desktop.
package Bouh
import java.util.concurrent.TimeUnit
class TapTempo
{
private val sample = 5
private val resetTime = TimeUnit.NANOSECONDS.convert(5, TimeUnit.SECONDS)
private val taps = ArrayList<Long>()
fun run() {
while (true) {
readLine()
tap()
displayBPM()
}
}
private fun tap() {
val currentTap = System.nanoTime()
checkResetTime()
if (taps.size == sample) {
taps.removeAt(0)
}
taps.add(currentTap)
}
private fun displayBPM()
{
if (taps.size == 1) {
println("[Hit a key one more time to start bpm computation...]")
return
}
println("Tempo: ${String.format("%.2f", getBPM())} bpm")
}
private fun getBPM(): Float {
return (taps.size - 1) / (taps.last() - taps[0].toFloat()) * TimeUnit.NANOSECONDS.convert(60, TimeUnit.SECONDS)
}
private fun checkResetTime() {
if (taps.isEmpty()) {
return
}
if (System.nanoTime() - taps.last() > resetTime) {
taps.clear()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment