tomDev
tomDev

Reputation: 5760

MediaPlayer Streaming Hanging App and Crashing on Slow Connections

I'm building a radio streaming app. Everything works great when I have a good internet connection, even when multitasking. The problem is without or with a poor internet connection.

The moment you tap the play button the app freezes and only resumes when the audio stream starts. With slow connections this can take a few seconds, hanging the app. Without Internet, the app eventually crashes after a while.

public class SoundService extends Service {
    MediaPlayer mp;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void onCreate() {

        mp = new MediaPlayer();
        try {
            mp.setDataSource("stream_url");
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            Log.v(TAG, "Error 1");
            onDestroy();
        } catch (IllegalStateException e) {
            e.printStackTrace();
            Log.v(TAG, "Error 2");
            onDestroy();
        } catch (IOException e) {
            e.printStackTrace();
            Log.v(TAG, "Error 3");
            onDestroy();
        }

        try {
            mp.prepare();
            mp.start();
        } catch (IllegalStateException e) {
            e.printStackTrace();
            Log.v(TAG, "Error 4");
            onDestroy();
        } catch (IOException e) {
            e.printStackTrace();
            Log.v(TAG, "Error 5");
            onDestroy();
        }
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        mp.start();
        return Service.START_NOT_STICKY;
    }

    public void onDestroy() {
        mp.stop();
        mp.release();
        stopSelf();
        super.onDestroy();
   }
}

This is how I start the stream (play button):

startService(new Intent(MainActivity.this, SoundService.class));

Without connection the app eventually gets the error number 5, but this occurs only when crashes, so it's too late do stop the player. Before that I don't get any "catch".

As a temporary workaround, I'm checking for internet connection before starting the stream. This way I can prevent the crash, but I still have a problem with the app hanging on slow connections.

Any ideas? Thanks!

Upvotes: 1

Views: 587

Answers (1)

Ehtesham Razi
Ehtesham Razi

Reputation: 11

use this code which might help you

 mediaPlayer.prepareAsync();
                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        mediaPlayer.start();
                    }
                });

Upvotes: 1

Related Questions