سؤال

I'm trying to start a media player that streams from a website. Right now, when "start" is pressed the entire activity just freezes for anywhere from 5 to 20 seconds while the stream connects. I'm trying to get the "player.start();" call to run in a thread to free up the activity while the stream connects but it's not working. Anyone have any ideas?

private void startplayer() {
    try { 
        stream_player = new MediaPlayer();
        stream_player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        stream_player = MediaPlayer.create(this, Uri.parse("http://stream-address"));

        Thread thread = new Thread(new Runnable() {
            public void run() {
                stream_player.start();
            }
        });
        thread.start();

        SetNotification(1, "live");
        liveON = true;
    } catch (Exception e) {
        Log.e(getClass().getName(), "Error starting to stream audio.", e);
        Toast.makeText(this, "Stream seems to be offline", Toast.LENGTH_LONG).show();
    }

}
هل كانت مفيدة؟

المحلول

Move the whole method to a separate thread. The part that takes the most time is the MediaPlayer.create() part, since this a synchronous call, which returns when the media player is ready to play.

An alternative is not to use create, but use the other format used in here which sets a listener before the prepare method, and when the listener is called, the start method is called.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top