views:

2060

answers:

4

I have my mp3 in byte[] (downloaded from service) and I would like to play it on my device similar to how you 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 than playing it, I am just hoping there is better way to do it.

+3  A: 

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.

Yoni Samlan
It's wise to always follow the API when it comes to dealing with media, unless you're absolutely sure your way is better/overcomes some glaring flaw in their implementation. In which case you should submit a bug report.
Sneakyness
So will the player initialize if we pass on a uri like http://server/song.mp3 to it?
Bohemian
So I was checking out this. And I passed the song location as Uri to the player. N it plays it fine.No file handling.I m testing it on 2.01/emulator
Bohemian
+1  A: 

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 ..

subbarao
If you are right, then it seems they need to update documentation -> http://developer.android.com/guide/topics/media/index.html#playfile
kape123
+4  A: 

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 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();

        // Tried reusing instance of media player
        // but that resulted in system crashes...  
        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();
    }
}
kape123
thanks works fine even for m4a files with aac encoding
Janusz