Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Audio by Decoding Base64

Tags:

java

android

My database has a lot of short audio that formatted base64. I want to play audio when the button is on clicking. Basically, I wrote this code but it doesn't work. (If it possible, The file had better doesn't writing to storage because this process have a delay)

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

        try{
            String url = "data:audio/mp3;base64,"+base64FormattedString;
            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepare();
            mediaPlayer.start();
        }
        catch(Exception e){
            e.printStackTrace();
        }

    }
});

And the stacktrace is here: https://gist.github.com/AliAtes/aa46261aba3d755fbbd1eba300356a5f

like image 518
ATES Avatar asked Mar 17 '17 09:03

ATES


1 Answers

With your API constraint, you can use AudioTrack. Furthermore, it's pretty easy. With AudioTrackyou can play byte[] audio data since API 3.

You just have to init your AudioTrack object with audio sample particularities:

AudioTrack audioTrack = new AudioTrack(...);

and call:

audioTrack.play();

Then, your decode your Base64 data:

byte[] data = Base64.decode(yourBase64AudioSample, Base64.DEFAULT);

and put it in audioTrack to playback:

int iRes = audioTrack.write(data, 0, data.length);

and TADAAA :)

... Don't forget to release after playing:

audioTrack.release();
like image 133
N0un Avatar answered Sep 18 '22 07:09

N0un