Home » Android » bytearray – Android – Playing mp3 from byte[]

bytearray – Android – Playing mp3 from byte[]

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have my mp3 file in byte[] (downloaded from an service) and I would like to play it on my device similar to how you can play files:

MediaPlayer mp = new MediaPlayer();
mp.setDataSource(PATH_TO_FILE);
mp.prepare();
mp.start();

But I can’t seem to find a way to do it. I wouldn’t mind saving file to phone and then playing it. How can I play the file, or download then play it?

How to&Answers:

OK, thanks to all of you but I needed to play mp3 from byte[] as I get that from .NET webservice (don’t wish to store dynamically generated mp3s on server).

In the end – there are number of “gotchas” to play simple mp3… here is code for anyone who needs it:

private MediaPlayer mediaPlayer = new MediaPlayer();
private void playMp3(byte[] mp3SoundByteArray) {
    try {
        // create temp file that will hold byte array
        File tempMp3 = File.createTempFile("kurchina", "mp3", getCacheDir());
        tempMp3.deleteOnExit();
        FileOutputStream fos = new FileOutputStream(tempMp3);
        fos.write(mp3SoundByteArray);
        fos.close();

        // resetting mediaplayer instance to evade problems
        mediaPlayer.reset();

        // In case you run into issues with threading consider new instance like:
        // MediaPlayer mediaPlayer = new MediaPlayer();                     

        // Tried passing path directly, but kept getting 
        // "Prepare failed.: status=0x1"
        // so using file descriptor instead
        FileInputStream fis = new FileInputStream(tempMp3);
        mediaPlayer.setDataSource(fis.getFD());

        mediaPlayer.prepare();
        mediaPlayer.start();
    } catch (IOException ex) {
        String s = ex.toString();
        ex.printStackTrace();
    }
}

EDIT: I’ve wrote this answer more than 4 years ago – obviously lots of things have changed since then. See Justin’s comment on how to reuse MediaPlayer instance. Also, I don’t know if .deleteOnExit() will work for you now – feel free to suggest improvement so that temp files do not pile up.

Answer:

I found an easy solution by encoding my MP3 file as Base64 (I already receive the data encoded from a Restful API service), and then creating a URL object. I tested it in Android 4.1.

public void PlayAudio(String base64EncodedString){
        try
        {
            String url = "data:audio/mp3;base64,"+base64EncodedString; 
            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepare();
            mediaPlayer.start();
        }
        catch(Exception ex){
            System.out.print(ex.getMessage());
        }
    }

Answer:

Starting Android MarshMellow (Version Code 23), there is new API that will make this possible.

MediaPlayer.setDataSource(android.media.MediaDataSource)

You can provide a custom implementation of MediaDataSource and wrap a byte[]. A basic implementation given below.

import android.annotation.TargetApi;
import android.media.MediaDataSource;
import android.os.Build;
import java.io.IOException;


@TargetApi(Build.VERSION_CODES.M)
public class ByteArrayMediaDataSource extends MediaDataSource {

    private final byte[] data;

    public ByteArrayMediaDataSource(byte []data) {
        assert data != null;
        this.data = data;
    }
    @Override
    public int readAt(long position, byte[] buffer, int offset, int size) throws IOException {
        System.arraycopy(data, (int)position, buffer, offset, size);
        return size;
    }

    @Override
    public long getSize() throws IOException {
        return data.length;
    }

    @Override
    public void close() throws IOException {
        // Nothing to do here
    }
}

Answer:

Not sure about bytearrays/bytestreams, but if you have a URL from the service, you can try setting the data source to a network URI by calling

setDataSource(Context context, Uri uri)

See the API docs.

Answer:

If you target API 23 and above, create a class like this

class MyMediaDataSource(val data: ByteArray) : MediaDataSource() {

override fun readAt(position: Long, buffer: ByteArray, offset: Int, size: Int): Int {

    if (position >= data.size) return -1 // -1 indicates EOF 

    val endPosition: Int = (position + size).toInt()
    var size2: Int = size
    if (endPosition > data.size)
        size2 -= endPosition - data.size

    System.arraycopy(data, position.toInt(), buffer, offset, size2)
    return size2
}

override fun getSize(): Long {
    return data.size.toLong()
}

override fun close() {}

}

and use like this

val mediaSource = MyMediaDataSource(byteArray)
MediaPlayer().apply {
    setAudioStreamType(AudioManager.STREAM_MUSIC)
    setDataSource(mediaSource)
    setOnCompletionListener { release() }
    prepareAsync()
    setOnPreparedListener { start() }
}

credits to krishnakumarp’s answer above and to this article

Answer:

wrong code:

 MediaPlayer mp = new MediaPlayer();
 mp.setDataSource(PATH_TO_FILE);
 mp.prepare();
 mp.start();

CORRECT CODE:

 MediaPlayer mp = new MediaPlayer();
 mp.setDataSource(PATH_TO_FILE);
 mp.setOnpreparedListener(this);
 mp.prepare();

//Implement OnPreparedListener 
OnPrepared() {
    mp.start();
 }

see API Demos ..