Sérgio LP
Sérgio LP

Reputation: 19

MediaPlayer stream from url

I have a simple app and I want to play a mp3 from a url.

when I add this code to OnCreate, the app crashes at opening:

try {
        mediaPlayer.setDataSource("http://www.freesfx.co.uk/rx2/mp3s/9/10183_1367780535.mp3");
        mediaPlayer.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }

Why? What's wrong with this part of the code?

Complete code:

  public class MediaStreamTest extends AppCompatActivity {
ImageButton bPlay;
ImageButton bStop;
MediaPlayer mediaPlayer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_media_stream_test);

    bPlay = (ImageButton)findViewById(R.id.btnPlay);
    bStop = (ImageButton)findViewById(R.id.btnStop);
    try {
        mediaPlayer.setDataSource("http://www.freesfx.co.uk/rx2/mp3s/9/10183_1367780535.mp3");
        mediaPlayer.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }

    bPlay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mediaPlayer.isPlaying()) {
                bPlay.setBackgroundResource(R.drawable.ic_play_arrow_24dp);
                mediaPlayer.pause();
            }
            else {
                bPlay.setBackgroundResource(R.drawable.ic_pause_24dp);
                mediaPlayer.start();
            }
        }
    });
}

}

Upvotes: 1

Views: 9315

Answers (1)

mmark
mmark

Reputation: 1204

The issue is because the MediaPlayer is not being initialized. That's why you are getting a null pointer exception when trying to use it.

Just add:

mediaPlayer = new MediaPlayer();

Before calling MediaPlayer.setDataSource method

Upvotes: 5

Related Questions