making a drum machine in android studio using a SoundPool

30 views Asked by At

I am trying to make a sort of drum machine app that can play prewritten patterns of different beats, to do this I am using a soundPool and a TimerTask but for some reason for BPMs under 120 the sound is very delayed, and not in sync with what I want it to sound like. for bpms above 120, it works perfectly though here is the code for the TimerTask

    private void PlayBeat(){ //plays the next beat according to the patterns selected
        beat = 0;
        timerTask = new TimerTask(){
            @Override
            public void run(){
                //saves the current beat in the pattern to play later
                String KcurrentNote = pocketList.get(currentPocket.substring(1)).substring(beat%16*2, beat%16*2 + 2);
                String SHcurrentNote = pocketList.get(currentPocket.substring(0,1)).substring(beat%16*2, beat%16*2 + 2);
                if(!pause){
                    if(Objects.equals(KcurrentNote, "KK")){ //plays Kick Drum if it should according to Kick Drum patterns
                        soundp.play(bID,1.0f,1.0f,0,0,1f);
                    }
                    switch (SHcurrentNote) { //cheks which sounds it needs to play out of the Snare/HiHat patterns
                        case "HH":
                            soundp.play(hhID, 1.0f, 1.0f, 0, 0, 1f);
                            break;
                        case "HS":
                            soundp.play(hhID, 1.0f, 1.0f, 0, 0, 1f);
                            soundp.play(sID, 1.0f, 1.0f, 0, 0, 1f);
                            break; 
                        case "SS":
                            soundp.play(sID, 1.0f, 1.0f, 0, 0, 1f);
                            break;
                        case "OH":
                            soundp.play(ohID, 1.0f, 1.0f, 0, 0, 1f);
                            break;
                    }
                    beat++;
                }

            }
        };
        //schedules the task to every 16th note of the bpm selected
        timer.scheduleAtFixedRate(timerTask,0,15000/Integer.parseInt(bpm.getText().toString())); 
    }

every time I try to play the beats they get messed up and play out of order if the bpm is lower than approx 120, I tried changing file types, making sure that the files themselves don't have a delay in them and I also tried to use timer.schedule() instead of timer.scheduleAtFixedRate() and nothing seemed to fix the problem

0

There are 0 answers