0

I am trying to play streaming music background and for that I am using music service class below:

public class MusicService extends Service implements
        OnErrorListener, MediaPlayer.OnCompletionListener {

    private static final int NOTIFICATION_ID = 1;
    private final IBinder mBinder = new ServiceBinder();
    MediaPlayer mPlayer;
    private int length = 0;
    private Notification mNotification;

    public MusicService() {
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        mPlayer.stop();
    }

    public class ServiceBinder extends Binder {
        public MusicService getService() {
            return MusicService.this;
        }
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mPlayer = new MediaPlayer();
        mPlayer.setOnCompletionListener(this);
        mPlayer.setOnErrorListener(this);

        if (mPlayer != null) {
            mPlayer.setLooping(true);
            mPlayer.setVolume(100, 100);
        }

        mPlayer.setOnErrorListener(new OnErrorListener() {

            public boolean onError(MediaPlayer mp, int what, int extra) {

                onError(mPlayer, what, extra);
                return true;
            }
        });
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // mPlayer.start();
        return START_STICKY;

    }

    public void startMusic(String path) {
        Toast.makeText(this, "pause music", Toast.LENGTH_SHORT).show();
        if (mPlayer.isPlaying()) {
            mPlayer.release();
        }
        try {
            SongController s = (SongController) DBControllerFactory.getController("queue", this);
            Log.d("MusicService", Config.SERVICE_ROOT_URL + "uploads/" + ((Song) s.select()[s.getTotalRows() - 1]).getFile() + ".mp3");
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.setDataSource(Config.SERVICE_ROOT_URL + "uploads/" + ((Song) s.select()[s.getTotalRows() - 1]).getFile() + ".mp3");
            mPlayer.prepare();  /////error at here
            mPlayer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void pauseMusic() {
        Toast.makeText(this, "pause music", Toast.LENGTH_SHORT).show();
        if (mPlayer.isPlaying()) {
            mPlayer.pause();
            length = mPlayer.getCurrentPosition();
        }
    }

    public void resumeMusic() {
        Toast.makeText(this, "resume music", Toast.LENGTH_SHORT).show();
        if (mPlayer.isPlaying() == false) {
            mPlayer.seekTo(length);
            mPlayer.start();
        }
    }

    public void stopMusic() {
        //setUpAsForeground("test");
        Toast.makeText(this, "stop music", Toast.LENGTH_SHORT).show();
        mPlayer.stop();
        mPlayer.release();
        mPlayer = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPlayer != null) {
            try {
                mPlayer.stop();
                mPlayer.release();
            } finally {
                mPlayer = null;
            }
        }

    }

    public boolean onError(MediaPlayer mp, int what, int extra) {

        Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
        if (mPlayer != null) {
            try {
                mPlayer.stop();
                mPlayer.release();
            } finally {
                mPlayer = null;
            }
        }
        return false;
    }

    void setUpAsForeground(String text) {
        Intent openIntent = new Intent(getApplicationContext(), MainScreenActivity.class);
        openIntent.putExtra("action", "opendrawer");
        PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),
                0,
                openIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        mNotification = new Notification();
        mNotification.tickerText = text;
        mNotification.icon = R.drawable.ic_launcher;
        mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
        mNotification.setLatestEventInfo(getApplicationContext(),
                getResources().getString(R.string.app_name), text, pi);
        startForeground(NOTIFICATION_ID, mNotification);
    }
}

when first time music is played , it works properly, but second time it gives following error:

java.io.IOException: Prepare failed.: status=0x1
 W/System.err﹕ at android.media.MediaPlayer._prepare(Native Method)
 W/System.err﹕ at android.media.MediaPlayer.prepare(MediaPlayer.java:1125)
......

but if I remove cache of my app from device It again works properly. so I think it's problem related to cache but I am unable to determine the problem can anyone help me please????

vedraiyani
  • 1
  • 1
  • 2

3 Answers3

0

Try resetting the mediaplayer before starting

if (mpObject.isPlaying())
            {
                mpObject.stop();
                mpObject.reset();
                mpObject.release();
            }
Arun Kumar
  • 194
  • 8
0

I think there is a problem in loading the file in your try catch block. And BTW where are you using these methods: 1.startMusic 2.pauseMusic 3.resumeMusic 4.stopMusic

I think on second time media player does not gets the source file to play and its mediaplayer.prepare in try catch block is not getting called. \

Try logging the lines where you are setting the source file to the mediaplayer to play.and let us know what you got in log cat.

I hope it would help you. And fell free to reply back if you need help.

ghost talker
  • 402
  • 5
  • 15
  • Thaks to reply...! I have already tried logging and getting correct source path and as I said when I play it first time it works properly but after that it's not working even if I close app and staring the app again but it works if I remove cache of app. – vedraiyani Mar 19 '15 at 14:29
  • with the help of your little explanation here I guessed there is a problem of media player is not getting released. or if it does then I think it should get create again with the same audio source file. So now you got to do some work. 1. You have to release , reset and destroy the mediaplayer instance 2. recreate the mediaplayer instance with the source 3. Start it again – ghost talker Mar 20 '15 at 05:56
  • THE PROBLEM : as you said "it's not working even if I close app and staring the app again but it works if I remove cache of app",,,, keep it in mind that you are working in service so you have to explicitly destroy it 0r stop and start it again. because in other case service will keep running and your onDestroy method is not going to call – ghost talker Mar 20 '15 at 06:01
  • vedraiyni if non of them works then try this code : 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(); } }); } this is for your idea to how to tackle and get prepare the mediaplayer when you are getting source file through url link . I hope this would work – ghost talker Mar 20 '15 at 06:06
  • Thanks to reply..! As you said, service may be in running state after closing app but I have also checked that it was not runing. I have also checked your code stil same problem – vedraiyani Mar 20 '15 at 15:29
  • What is the source of file that you are trying to play . if it is in a external folder then please make sure that you have in your manifest file. BTW where is file located in your app? – ghost talker Mar 22 '15 at 10:42
0

I think this is your solution. please let me know if this help for you. If it also do not work for you then you need to share the source code of your SongController class

Community
  • 1
  • 1
ghost talker
  • 402
  • 5
  • 15