Monday, 5 April 2021

Media player stopping after some time and Seekbar OnTouch is not working

I am trying to create online music player where I can play songs from URL. Almost I am done with everything but I am facing two issues -

  1. Seekbar OnTouch is not working - When I am trying to adjust Seekbar manually then its playing next song (Error is E/MediaPlayerNative: error (1, -2147483648))and some time it going back to original potion (i.e. 00:00 and no error)
  2. Media player stopping after some time - After 5 min media player is stopping and next song is starting

Below are some points regarding my app -

  1. Playing song from URL where url is HTTPS
  2. All Audio files are in MP3 format
  3. All Audio files are 320kbps bitrate
  4. Audio file length is 01:00 to 02:30:00 (1 min to 2.5 hrs)

Below is my code

JAVA code -

public class NewlyAdded extends AppCompatActivity implements MediaPlayer.OnBufferingUpdateListener, AudioManager.OnAudioFocusChangeListener {
    private AudioManager mAudioManager;
    TextView t1;
    int V = 1, temp, currentplay;
    Button next, prev, Play;
    private static MediaPlayer mediaPlayer;
    public static int oneTimeOnly = 0;
    private boolean init = false;
    private SeekBar seekBar;
    TextView TotalTime, RemainingTime;
    PlayFileFromURL asyncTask = null;
    ProgressDialog dialog;
    private int mediaFileLengthInMilliseconds;
    String[] mobileArray = {
            "Song Title 1",
            "Song Title 2",
            "Song Title 3",
    };

    String[] playurl = {
            "https://SongURL1.mp3",
            "https://SongURL2.mp3",
            "https://SongURL3.mp3",
    };


    @SuppressLint("ClickableViewAccessibility")
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.newlyaddedlayout);

        Objects.requireNonNull(getSupportActionBar()).setDisplayShowHomeEnabled(true);
        getSupportActionBar().setLogo(R.mipmap.ic_launcher_round);
        getSupportActionBar().setDisplayUseLogoEnabled(true);
        getSupportActionBar().setSubtitle("Activity");

        ArrayAdapter adapter = new ArrayAdapter<>(this,
                R.layout.listlayout, mobileArray);


        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

        t1 = findViewById(R.id.textview);
        t1.startAnimation(AnimationUtils.loadAnimation(NewlyAdded.this, R.anim.translate));

        ListView listView = findViewById(R.id.listAbhang);
        listView.setAdapter(adapter);
        prev = findViewById(R.id.backward);
        next = findViewById(R.id.forward);
        Play = findViewById(R.id.play);
        TotalTime = findViewById(R.id.total_time);
        RemainingTime = findViewById(R.id.remaining_time);
        RateUs.app_launched(this);

        prev.setEnabled(false);
        next.setEnabled(false);
        Play.setEnabled(false);
        mediaPlayer = new MediaPlayer();
        asyncTask = new PlayFileFromURL();
        dialog = new ProgressDialog(this);
        seekBar = findViewById(R.id.seekbar);
        seekBar.setMax(99); // 100% (0~99)
        seekBar.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mediaPlayer.isPlaying()) {
                    SeekBar seekBar = (SeekBar) v;
                    int playPosition = (mediaFileLengthInMilliseconds / 100) * seekBar.getProgress();
                    mediaPlayer.seekTo(playPosition);
                }
                return false;
            }
        });
        listView.setOnItemClickListener(
                new ListView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        String cities = String.valueOf(parent.getItemAtPosition(position));
                        t1.setText(cities);
                        try {
                            prev.setEnabled(true);
                            next.setEnabled(true);
                            Play.setEnabled(true);
                            temp = position;
                            currentplay = temp;
                            asyncTask = new PlayFileFromURL();
                            asyncTask.execute(playurl[currentplay]);
                            Log.i("Temp_id", String.valueOf(temp));

                        } catch (WindowManager.BadTokenException e) {
                            //use a log message
                        }
                    }

                });


        Play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if (V == 0) {
                    V = 1;
                    mediaPlayer.start();
                    updateSeekBar();
                    Toast.makeText(getApplicationContext(), "Playing sound", Toast.LENGTH_SHORT).show();
                    Play.setBackgroundResource(R.drawable.pause_);
                    if (oneTimeOnly == 0) {
                        oneTimeOnly = 1;
                    }

                } else {
                    V = 0;
                    mediaPlayer.pause();
                    updateSeekBar();
                    Play.setBackgroundResource(R.drawable.play_);
                    Toast.makeText(getApplicationContext(), "Pausing " +
                            "sound", Toast.LENGTH_SHORT).show();
                }


            }
        });

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (currentplay == playurl.length - 1) {
                        Snackbar snackbar;
                        snackbar = Snackbar.make(findViewById(android.R.id.content), "This is Last Song", Snackbar.LENGTH_LONG);
                        View snackBarView = snackbar.getView();
                        snackBarView.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                        TextView textView = snackBarView.findViewById(com.google.android.material.R.id.snackbar_text);
                        textView.setTextColor(getResources().getColor(R.color.white));
                        snackbar.show();
                    } else {
                        if (asyncTask != null) {
                            asyncTask.cancel(true);
                        }
                        asyncTask = new PlayFileFromURL();
                        currentplay = currentplay + 1;
                        asyncTask.execute(playurl[currentplay]);
                        t1.setText(mobileArray[currentplay]);

                    }

                    //currentplay=currentplay+1;
                    //play(playurl[currentplay]);
                    //t1.setText(mobileArray[currentplay]);

                } catch (WindowManager.BadTokenException e) {
                    //use a log message
                }
            }
        });
        prev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {

                    if (currentplay == 0) {
                        Snackbar snackbar;
                        snackbar = Snackbar.make(findViewById(android.R.id.content), "This is First Song", Snackbar.LENGTH_LONG);
                        View snackBarView = snackbar.getView();
                        snackBarView.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                        TextView textView = snackBarView.findViewById(com.google.android.material.R.id.snackbar_text);
                        textView.setTextColor(getResources().getColor(R.color.white));
                        snackbar.show();

                    } else {
                        if (asyncTask != null) {
                            asyncTask.cancel(true);
                        }
                        asyncTask = new PlayFileFromURL();
                        currentplay = currentplay - 1;
                        asyncTask.execute(playurl[currentplay]);
                        t1.setText(mobileArray[currentplay]);
                    }

                    //currentplay=currentplay-1;
                    //play(playurl[currentplay]);
                    //t1.setText(mobileArray[currentplay]);

                } catch (WindowManager.BadTokenException e) {
                    //use a log message
                }
            }
        });

    }

    protected void onDestroy() {
        super.onDestroy();
        // TODO Auto-generated method stub
        mAudioManager.abandonAudioFocus(this);
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        finish();
    }


    /**
     * Called when leaving the activity
     */
    @Override
    public void onPause() {
        super.onPause();
    }

    /**
     * Called when returning to the activity
     */
    @Override
    public void onResume() {
        super.onResume();
    }


    @SuppressLint("SetTextI18n")
    @Override
    public void onBackPressed() {

        startActivity(new Intent(NewlyAdded.this, MainActivity.class));

    }

    @Override
    public void onAudioFocusChange(int focusChange) {
        if (focusChange <= 0) {
            //LOSS -> PAUSE
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                Play.setBackgroundResource(R.drawable.play_);
            }
        } else {
            //GAIN -> PLAY
            if (mediaPlayer != null) {
                mediaPlayer.start();
                updateSeekBar();
                Play.setBackgroundResource(R.drawable.pause_);
            }
        }
    }

    /**
     * Background Async Task to Play file
     */
    @SuppressLint("StaticFieldLeak")
    class PlayFileFromURL extends AsyncTask<String, String, String> {

        @SuppressLint("ResourceAsColor")
        @Override
        protected void onPreExecute() {

            mediaPlayer.stop();
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            dialog.setMessage("\nLoading It may take time according to your network speed");
            TextView title = new TextView(NewlyAdded.this);
            title.setText("Loading, please wait.");
            title.setBackgroundColor(R.color.colorAccent);
            title.setPadding(20, 20, 20, 20);
            title.setGravity(Gravity.CENTER);
            title.setTextColor(Color.WHITE);
            title.setTextSize(20);
            dialog.setCustomTitle(title);
            dialog.setCancelable(false);
            dialog.show();
        }

        @Override
        protected String doInBackground(String... f_url) {

            try {
                mediaPlayer.setDataSource(f_url[0]);
                mediaPlayer.prepare();
            } catch (Exception ignored) {

            }

            int duration = mediaPlayer.getDuration();
            Log.i("time", DateUtils.formatElapsedTime(duration / 1000) + " ms");
            mediaFileLengthInMilliseconds = duration;
            Log.i("Temp_id", String.valueOf(temp));
            Log.i("Temp_id", Arrays.toString(f_url));
            return null;
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            asyncTask.cancel(true);
            Toast.makeText(NewlyAdded.this, "AsyncTask is stopped", Toast.LENGTH_LONG).show();
        }

        @Override
        protected void onPostExecute(final String file_url) {

            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            try {
                mediaPlayer.start();
            } catch (Exception ex) {
                String err = (ex.getMessage() == null) ? "SD Card failed" : ex.getMessage();
                Log.e("sdcard-err2:", err);
            }
            TotalTime.setText(DateUtils.formatElapsedTime(mediaFileLengthInMilliseconds / 1000));
            Play.setBackgroundResource(R.drawable.pause_);
            updateSeekBar();
            if (dialog.isShowing()) {
                dialog.dismiss();
             
            }

            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                public void onCompletion(MediaPlayer mp) {
                    Log.i("Temp_id", String.valueOf(temp));
                    try {
                        asyncTask.cancel(true);
                        asyncTask = new PlayFileFromURL();
                        if (temp == playurl.length) {
                            temp = 0;
                            asyncTask.execute(playurl[temp]);
                            t1.setText(mobileArray[temp]);
                            Log.i("Temp_id if", String.valueOf(temp));
                        } else {
                            temp = temp + 1;
                            asyncTask.execute(playurl[temp]);
                            Log.i("Temp_id else", String.valueOf(temp));
                            t1.setText(mobileArray[temp]);
                        }
                    } catch (ArrayIndexOutOfBoundsException exception) {
                        temp = 0;
                        asyncTask.execute(playurl[temp]);
                        t1.setText(mobileArray[temp]);
                    }
                }
            });
        }
    }

    private void updateSeekBar() {
        seekBar.setProgress((int) (((float) mediaPlayer.getCurrentPosition() / mediaFileLengthInMilliseconds) * 100));
        if (mediaPlayer.isPlaying()) {
            Runnable updater = new Runnable() {
                @Override
                public void run() {
                    updateSeekBar();
                    RemainingTime.setText(DateUtils.formatElapsedTime(mediaPlayer.getCurrentPosition() / 1000));
                }
            };
            seekBar.post(updater);
        }
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        seekBar.setSecondaryProgress(percent);
    }
}

XML file -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    
    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:maxLines="1"
        android:singleLine="true"
        android:text="@string/try_our_other_apps"
        android:textColor="#ff544e"
        android:textSize="20sp" />

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textColor="#000000">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="105dp"
            android:orientation="vertical">

            <ListView
                android:id="@+id/listAbhang"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:choiceMode="singleChoice"
                android:listSelector="#41000000"
                android:textColor="#000000" />

        </LinearLayout>

        <GridLayout
            android:layout_width="350dp"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:orientation="vertical">

            <GridLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <SeekBar
                        android:id="@+id/seekbar"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center" />

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content">

                        <RelativeLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:orientation="horizontal">

                            <androidx.appcompat.widget.AppCompatTextView
                                android:id="@+id/remaining_time"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_alignParentStart="true"
                                android:fontFamily="serif"
                                android:text="@string/time"
                                android:textSize="15sp" />

                            <androidx.appcompat.widget.AppCompatTextView
                                android:id="@+id/total_time"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_alignParentEnd="true"
                                android:fontFamily="serif"
                                android:text="@string/time"
                                android:textSize="15sp" />

                        </RelativeLayout>

                    </LinearLayout>
                </LinearLayout>
            </GridLayout>

            <GridLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginTop="3dp">

                <Button
                    android:id="@+id/backward"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_marginEnd="10dp"
                    android:layout_marginRight="10dp"
                    android:background="@drawable/last" />

                <Button
                    android:id="@+id/play"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:background="@drawable/play_" />

                <Button
                    android:id="@+id/forward"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_marginStart="10dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginTop="0dp"
                    android:background="@drawable/next" />

            </GridLayout>

        </GridLayout>

    </RelativeLayout>

</LinearLayout>

It look like -

enter image description here

I tried below solutions -

Mediaplayer error (-38,0) and error (1,-1010)

Android MediaPlayer Error (1,-1010)

MediaPlayer stop playing after about 5 seconds

Android : seekbar touch not working while playing music?

Android SeekBar progress is not working?

Please help me to fix issue. Thank you in Advance.



from Media player stopping after some time and Seekbar OnTouch is not working

No comments:

Post a Comment