Home > Software design >  How to play a 20ms audio file in Android Studio using a for loop?
How to play a 20ms audio file in Android Studio using a for loop?

Time:09-24

I have a binary string and I want to play two sounds based on the type of bit. I have put a 1200hz WAV file and 1600hz WAV file in the raw folder.

Now I want to iterate through this binary string, and if the bit is zero, I want to play 1200hz wav file and if the bit is one, then I want to play 1600hz wav file. Each of this wav file is 20 milliseconds in length.

For example, if the 3rd character in the binary string is zero, then I want to play the 1200hz frequency wav file for 20ms, and then head to the next character, i.e., the 4th character and play it's respective sound.

However, my code is not working like I wanted it to. I'm new to android studio and I don't know how to resolve it. Please help me.

Here's my code

    private void playTone(){
        String bin_string = "011100101010111010101011101000";

        final MediaPlayer f1200 = MediaPlayer.create(this, R.raw.wave1200hz);
        final MediaPlayer f1600 = MediaPlayer.create(this, R.raw.wave1600hz);

        for(int i=0; i<bin_string.length(); i  ){
            if(bin_string.charAt(i)=='0'){
                //play 1200hz
                f1200.start();
            }
            if(bin_string.charAt(i)=='1'){
                //play 1600hz
                f1600.start();
            }
        }

        f1200.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
                mp.release();
            }
        });

        f1600.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
                mp.release();
            }
        });
    }

CodePudding user response:

The iteration is not correct. You should proceed to next char inside onCompletion. The approximate way to do it as follows:

Make an int counter as global field. Than method next() that does the following

public void next(){
    if(bin_string.charAt(counter)=='0'){
                    //play 1200hz
                    f1200.start();
                }
                if(bin_string.charAt(counter)=='1'){
                    //play 1600hz
                    f1600.start();
                }
}

Than inside the oncompletion add

counter  ;
if (counter< bin_string.length){
next();
} else {
mp.release();
counter=0;
}

Also you should remember to release the second mediaplayer.

  • Related