Search code examples
androidaudiomedia-playerandroid-mediaplayer

Android play beep sound, every n milliseconds


I created an Android application that is like a metronome. Actually I want to play a beep sound every n milliseconds. I use MediaPlayer and timer for this.

My code is like this:

Soloution 1:

start_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Timer timer = new Timer("MetronomeTimer", true);
            TimerTask tone = new TimerTask() {
                @Override
                public void run() {
                    //Log
                    DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss:SS");
                    Date date = new Date();
                    j++;
                    Log.i("Beep", df.format(date) + "_____" + j);
                    //Play sound
                    music = MediaPlayer.create(MainActivity.this, R.raw.beep);
                    music.start();
                }
            };
            timer.scheduleAtFixedRate(tone, 500, 500); // every 500 ms 
        }
    });

When I run this code, everything is OK. But after 15 times loop, line of Log works fine, but sound is muted. And occasionally every 15, or 20 Log, sound plays and stop.

Solution 2:

I move this line:

music = MediaPlayer.create(MainActivity.this, R.raw.beep);

out of TimerTask (like this):

start_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            music = MediaPlayer.create(MainActivity.this, R.raw.beep);

            Timer timer = new Timer("MetronomeTimer", true);
            TimerTask tone = new TimerTask() {
                @Override
                public void run() {
                    //Log
                    DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss:SS");
                    Date date = new Date();
                    j++;
                    Log.i("Beep", df.format(date) + "_____" + j);
                    //Play sound
                    music.start();
                }
            };
            timer.scheduleAtFixedRate(tone, 500, 500); // every 500 ms 
        }
    });

This code is OK too until 500 ms for repeating. when period time decrease to 400 or 300 ms, every 2 Log, one sound beeps.

How to repair this code that work fine.


Solution

  • SoundPool is better for playing short sounds that are loaded from memory. I have also had problems implementing MediaPlayer, SoundPool has just been a much easier and lower latency experience.

    If you set .setMaxStreams() to a number above 1 you shouldn't get any muted sounds. Try and experiment.