17

I'm having a crack at using the MediaPlayer object and not having much success. If I add a sound asset to my raw folder and call it using the int value within R, it works fine. But I want to be able to pull things off of url.

According to all of the documentation I've read setDataSource() should accept a string param with a url to a file.

I keep getting an IO exception on the prepare() statement. I've even tried copying the file locally and still no dice.

Anyone have any ideas?

MediaPlayer mp = new MediaPlayer();
try {
        mp.setDataSource("http://www.urltofile.com/file.mp3");
        mp.prepare();
        mp.start();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
Kyle
  • 10,839
  • 17
  • 53
  • 63

2 Answers2

23

Try MediaPlayer.create(), you also may want to start only after player is actually ready, for example:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MediaPlayer player = MediaPlayer.create(this, Uri.parse("http://www.urltofile.com/file.mp3"));
    player.setOnPreparedListener(new OnPreparedListener() { 
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.start();
        }
    });
}
Konstantin Burov
  • 68,980
  • 16
  • 115
  • 93
  • 3
    Works great with external URLs (eg, "http://google.com/") but throws an exception when trying local assets (eg, "file://android_asset/sound.mp3") :( – richtaur Jan 12 '11 at 11:56
  • 1
    @richtaur what makes you to use android assets instead of regular resources? MediaPlaye.create(Context context, int resid) should work great for app internal media files. – Konstantin Burov Jan 12 '11 at 12:38
  • Would just make my stuff more organized :) Resources folder is good enough. – richtaur Jan 15 '11 at 06:49
14

For streams, you should call prepareAsync(), which returns immediately, rather than blocking until enough data has been buffered.

Andro Selva
  • 53,910
  • 52
  • 193
  • 240
Ihor DIM
  • 689
  • 1
  • 10
  • 22