1

I'm making an Metronome app. I wish to have it count precisely 4 beats in a loop with an accent on the first beat.

Inside Android Studio on my simulator it works fine, but on my actual phone (Galaxy J3 - 2018, Android v9) that time interval is not stable at all it's very random.

I have tried Threads, Coroutines, Handlers but nothing seems to work. I also had a look at the Timer objects, I was trying to copy someone's code on Stack Overflow and refactor it but without any success

This is my code so far (which works on the emulator)

timer = 5000
timeSignatureTop = 4
accentPlayed = false
measureCount = 1

Thread {


            while (!stopButtonPressed) {

                Log.d("Thread running", "running")

                if (!accentPlayed) {
                    mediaPlayerAccent!!.start()
                    measureCount++
                    accentPlayed = true
                }

                else if (measureCount < timeSignatureTop) {
                    mediaPlayerBeat!!.start()
                    measureCount++
                }

                else if (measureCount == timeSignatureTop) {
                    mediaPlayerBeat!!.start()
                    measureCount = 1
                    accentPlayed = false
                }

                Thread.sleep(timer.toLong())

            }

            Log.d("Thread stopped", "stopped")
            return@Thread

    }.start()
TylerH
  • 20,799
  • 66
  • 75
  • 101
gab
  • 43
  • 5
  • Can someone clarify if I need to set a "priority" thread on my app or something like that. I don't why it's behaving randomly on my phone but not on the emulator. – gab Mar 24 '23 at 19:47
  • I also tried to refactor this code: https://github.com/zachchurchill/metronome-kotlin/blob/master/app/src/main/java/com/zachchurchill/metronome/Metronome.kt but without much success, it's by the most stable interval I got, but still random intervals occur – gab Mar 24 '23 at 20:46
  • Have you tried running a non-debug build? – Tenfour04 Mar 25 '23 at 12:54
  • No yet, but I tried something, in the link I above, I switched the my custom mp3 sound media. When I switch the sound to a ToneGenerator (native) the issue is gone. val toneSound = ToneGenerator.TONE_PROP_BEEP val toneGenerator = ToneGenerator(AudioManager.STREAM_MUSIC, 100) instead oy me custom audio: val mediaPlayerBeat = MediaPlayer.create(this@MainActivity, R.raw.normal_beat) – gab Mar 25 '23 at 13:48
  • I tried with a release APK version, same issue, it's more stable but not 100% consistent as in you can hear clear when the interval goes wrong and it's more relatively often – gab Mar 25 '23 at 14:48
  • .ogg is more performant than mp3, and I think wav is even better than ogg, since it doesn’t have to be decompressed. – Tenfour04 Mar 25 '23 at 16:17

0 Answers0