Ananya Srivastav Ananya Srivastav - 1 month ago 7
Android Question

mp3 file not playing in the app

I am trying to play this song via server but its not playing up only the seekbar is moving from start to end and no info. is shown and song is also not playing.
My code of the player activity is:

MyPlayer.java

public class MyPlayer extends Fragment implements View.OnClickListener, MediaPlayer.OnBufferingUpdateListener, OnCompletionListener, View.OnTouchListener {

@Nullable
AudioManager audioManager;
ImageButton nextButton,backButton,repeat,volumehigh,volumelow, playpause;
ToggleButton shufful;
SeekBar seekbar, seekbar1;
TextView artistname,mp3ename,starttime,totaltime;
String strText= "" ,strText1="";
MediaPlayer myMediaPlayer;
private MediaPlayer mediaPlayer;
private int mediaFileLengthInMilliseconds; // this value contains the song duration in milliseconds. Look at getDuration() method in MediaPlayer class
public EditText editTextSongURL;
String url = "https://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3";

private final Handler handler = new Handler();
private SeekBar seekBarProgress;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// return super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.player, container, false);
initView();
ArtistSong songFromArtist = new ArtistSong();
strText = songFromArtist.getMp3();
strText1 = songFromArtist.getName();

artistname = (TextView) view.findViewById(R.id.nameArtistaa);
mp3ename = (TextView) view.findViewById(R.id.mp3Nameaa);
totaltime = (TextView) view.findViewById(R.id.totalTimeaa);
starttime = (TextView) view.findViewById(R.id.startTimeaa);
playpause = (ImageButton) view.findViewById(R.id.pauseaa);
nextButton = (ImageButton) view.findViewById(R.id.forwardaa);
backButton = (ImageButton) view.findViewById(R.id.backaa);
repeat = (ImageButton) view.findViewById(R.id.loopaa);
shufful = (ToggleButton) view.findViewById(R.id.icnshuffleaa);
volumehigh = (ImageButton) view.findViewById(R.id.icnvolumehightaa);
volumelow = (ImageButton) view.findViewById(R.id.lowvolumeaa);
seekbar = (SeekBar) view.findViewById(R.id.seekBaraa);
seekbar1 = (SeekBar) view.findViewById(R.id.seekBar2aa);
audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);

seekbar1.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));

seekbar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

// textview.setText("Media Volume : " + i);

audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0);
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {

}
});
return view;
}

private void initView() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}

/** Method which updates the SeekBar primary progress by current song playing position*/
private void primarySeekBarProgressUpdater() {
seekBarProgress.setProgress((int) (((float) mediaPlayer.getCurrentPosition() / mediaFileLengthInMilliseconds)*100));
// This math construction give a percentage of "was playing"/"song length"
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
primarySeekBarProgressUpdater();
}
};
handler.postDelayed(notification,1000);
}
}

@Override
public void onClick(View v) {
if(v.getId() == R.id.pauseaa){
/** ImageButton onClick event handler. Method which start/pause mediaplayer playing */
try {
mediaPlayer.setDataSource(url.toString());
// setup song from https://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3 URL to mediaplayer data source
mediaPlayer.prepare();
// you must call this method after setup the datasource in setDataSource method. After calling prepare() the instance of MediaPlayer starts load data from URL to internal buffer.
} catch (Exception e) {
e.printStackTrace();
}

mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets the song length in milliseconds from URL

if(!mediaPlayer.isPlaying()){
mediaPlayer.start();
playpause.setImageResource(R.drawable.pause);
}else {
mediaPlayer.pause();
playpause.setImageResource(R.drawable.play);
}

primarySeekBarProgressUpdater();
}
}


public boolean onTouch(View v, MotionEvent event) {
if(v.getId() == R.id.seekBaraa){
/** Seekbar onTouch event handler. Method which seeks MediaPlayer to seekBar primary progress position*/
if(mediaPlayer.isPlaying()){
SeekBar sb = (SeekBar)v;
int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100) * sb.getProgress();
mediaPlayer.seekTo(playPositionInMillisecconds);
}
}
return false;
}

@Override
public void onCompletion(MediaPlayer mp) {
/** MediaPlayer onCompletion event handler. Method which calls then song playing is complete*/
playpause.setImageResource(R.drawable.play);
}

@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
/** Method which updates the SeekBar secondary progress by current song loading from URL position*/
seekBarProgress.setSecondaryProgress(percent);
}

}

Answer

Just try to use :

package com.android.sampleapp;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ToggleButton;

import java.io.IOException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener, View.OnTouchListener {
    AudioManager audioManager;
    ImageButton nextButton, backButton, repeat, volumehigh, volumelow, playpause;
    ToggleButton shufful;
    SeekBar seekbar, seekbar1;
    TextView artistname, mp3ename, starttime, totaltime;
    String strText = "", strText1 = "";
    MediaPlayer myMediaPlayer;
    private MediaPlayer mediaPlayer;
    private int mediaFileLengthInMilliseconds; // this value contains the song duration in milliseconds. Look at getDuration() method in MediaPlayer class 
    public EditText editTextSongURL;
    String url = "https://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3";

    private final Handler handler = new Handler();
    private SeekBar seekBarProgress;


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

        initView();

        artistname = (TextView) findViewById(R.id.nameArtistaa);
        mp3ename = (TextView) findViewById(R.id.mp3Nameaa);
        totaltime = (TextView) findViewById(R.id.totalTimeaa);
        starttime = (TextView) findViewById(R.id.startTimeaa);
        playpause = (ImageButton) findViewById(R.id.pauseaa);
        nextButton = (ImageButton) findViewById(R.id.forwardaa);
        backButton = (ImageButton) findViewById(R.id.backaa);
        repeat = (ImageButton) findViewById(R.id.loopaa);
        shufful = (ToggleButton) findViewById(R.id.icnshuffleaa);
        volumehigh = (ImageButton) findViewById(R.id.icnvolumehightaa);
        volumelow = (ImageButton) findViewById(R.id.lowvolumeaa);
        seekbar = (SeekBar) findViewById(R.id.seekBaraa);
        seekbar1 = (SeekBar) findViewById(R.id.seekBar2aa);
        audioManager = (AudioManager) MainActivity.this.getSystemService(Context.AUDIO_SERVICE);


        seekBarProgress = seekbar; // TODO: 24/10/16 In this link missing

        seekbar1.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));

        seekbar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

// textsetText("Media Volume : " + i); 

                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        playpause.setOnClickListener(this); // TODO: 24/10/16 In this link missing
    }

    /**
     * Method which updates the SeekBar primary progress by current song playing position
     */
    private void primarySeekBarProgressUpdater() {
        seekBarProgress.setProgress((int) (((float) mediaPlayer.getCurrentPosition() / mediaFileLengthInMilliseconds) * 100));
// This math construction give a percentage of "was playing"/"song length" 
        if (mediaPlayer.isPlaying()) {
            Runnable notification = new Runnable() {
                public void run() {
                    primarySeekBarProgressUpdater();
                }
            };
            handler.postDelayed(notification, 1000);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.pauseaa) {

/** ImageButton onClick event handler. Method which start/pause mediaplayer playing */
            try {
                mediaPlayer.setDataSource(String.valueOf(Uri.parse(url)));
// setup song from hrupin.com/wp-content/uploads/… URL to mediaplayer data source 
                mediaPlayer.prepare();
// you must call this method after setup the datasource in setDataSource method. After calling prepare() the instance of MediaPlayer starts load data from URL to internal buffer.
            } catch (Exception e) {
                e.printStackTrace();
            }

            mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets the song length in milliseconds from URL

            if (!mediaPlayer.isPlaying()) {
                mediaPlayer.start();
                playpause.setImageResource(android.R.drawable.ic_media_pause);
            } else {
                mediaPlayer.pause();
                playpause.setImageResource(android.R.drawable.ic_media_play);
            }

            primarySeekBarProgressUpdater();
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
/** MediaPlayer onCompletion event handler. Method which calls then song playing is complete*/
        playpause.setImageResource(android.R.drawable.ic_media_play);
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
/** Method which updates the SeekBar secondary progress by current song loading from URL position*/
        seekBarProgress.setSecondaryProgress(percent);
    }


    private void initView() {
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(url);
            mediaPlayer.setOnBufferingUpdateListener(this);
            mediaPlayer.setOnCompletionListener(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (v.getId() == R.id.seekBaraa) {
/** Seekbar onTouch event handler. Method which seeks MediaPlayer to seekBar primary progress position*/
            if (mediaPlayer.isPlaying()) {
                SeekBar sb = (SeekBar) v;
                int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100) * sb.getProgress();
                mediaPlayer.seekTo(playPositionInMillisecconds);
            }
        }
        return false;
    }
}
Comments