Base64 audio decoding

There are many short base64 formatted audio formats in my database. I want to play audio when the button is pressed. Basically, I wrote this code, but it does not work. (If possible, the file is better not written to storage, because this process has 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 stacktrace is here: https://gist.github.com/AliAtes/aa46261aba3d755fbbd1eba300356a5f

+4
source share
2 answers

With your API limitation, you can use AudioTrack . It is also quite easy. With, AudioTrackyou can play audio files byte[]since API 3.

AudioTrack :

AudioTrack audioTrack = new AudioTrack(...);

:

audioTrack.play();

Base64:

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

AudioTrack :

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

TADAAA:)

... :

audioTrack.release();
+3

, MediaDataSource setDataSource .

, - :

// first decode the data to bytes
byte[] data = Base64.decode(base64FormattedString, Base64.DEFAULT);
mediaPlayer.setDataSource(new MediaDataSource() {
    @Override
    public long getSize() {
        return data.length;
    }

    @Override
    public int readAt(long position, byte[] buffer, int offset, int size) {
        int length = getSize();
        if (position >= length) return -1; // EOF
        if (position + size > length) // requested more than available
            size = length - position; // set size to maximum size possible
                                      // at given position

        System.arraycopy(data, (int) position, buffer, offset, size);
        return size;
    }

    @Override
    public synchronized void close() throws IOException {

    }
});

MediaDataSource .

: 23 API. -23 byte[] ( , URL- ). , , , , .

2: N0un answer, , API 3 AudioTrack MediaPlayer.

+1

Source: https://habr.com/ru/post/1672541/


All Articles