Android MediaPlayer change live stream's URL - android

I have a problem with changing URL of live stream in the MediaPlayer instance. When I tap on a ListView item for a first time, live streaming is started and video is displayed, but if I click on another object in the ListView, stream is not changed, the same stream continues to play which was executed at first time.
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, VideoControllerView.MediaPlayerControl {
SurfaceView videoSurface;
MediaPlayer player;
VideoControllerView controller;
ArrayList<Channel> channels;
Channel clickedChannel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoSurface = (SurfaceView) findViewById(R.id.videoSurface);
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
controller = new VideoControllerView(this);
player = new MediaPlayer();
channels = new ArrayList<Channel>();
CreateChannels();
ListView lvMain = (ListView) findViewById(R.id.lvMain);
CustomAdapter adapter = new CustomAdapter(this, channels);
lvMain.setAdapter(adapter);
lvMain.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(LOG_TAG, "itemClick: position = " + position + ", id = "
+ id);
clickedChannel = channels.get(position);
}
}
}
PlayStream(clickedChannel.Streams[0].URL);
}
});
}
public void PlayStream(String URL) {
try {
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(this, Uri.parse(URL));
player.setOnPreparedListener(this);
player.prepareAsync();
player.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// missed code
#Override
public boolean onTouchEvent(MotionEvent event) {
controller.show();
return false;
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
player.setDisplay(holder);
}
#Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(this);
controller.setAnchorView((FrameLayout) findViewById(R.id.videoSurfaceContainer));
player.start();
}
}

Solved my problem by recreating player instance every time
public void PlayStream(String URL) {
releaseMP();
try {
player = new MediaPlayer();
player.setDisplay(videoHolder);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(this, Uri.parse(URL));
player.setOnPreparedListener(this);
player.prepareAsync();
player.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void releaseMP() {
if (player != null) {
try {
player.release();
player = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMP();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}

Related

It has just one issue that it plays multiple songs if selected, rest everything works fine

the issue is, I have checked whether media player is null or not, if not I have applied release() method but still when I select another song to play, it plays new song but it doesn't stop the previous one. While playing next or previous on click also works fine. so why it is not detecting that mediaplayer is playing.
here is java code.
public class Musicplay extends AppCompatActivity implements View.OnClickListener {
Button play,next,previous;
TextView songmar;
SeekBar seekBar;
MediaPlayer mediaPlayer;
int position,idr;
Handler handler=new Handler();
Handler vindler=new Handler();
Uri uri;
int max;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playdisplay);
Intent i=getIntent();
position=i.getIntExtra("position",0);
play=findViewById(R.id.pause);
next=findViewById(R.id.next);
previous=findViewById(R.id.previous);
songmar=findViewById(R.id.songnamemar);
songmar.setSelected(true);
songmar.setText(Musiclist.songname.get(position));
seekBar=findViewById(R.id.seekBar);
if(mediaPlayer==null)
{
Log.d("null","null");
}
else {
if(mediaPlayer.isPlaying())
{
mediaPlayer.stop();
mediaPlayer.release();
}
else {
mediaPlayer.release();
}
}
uri=Uri.parse(String.valueOf(new File(Musiclist.songpath.get(position))));
mediaPlayer=MediaPlayer.create(Musicplay.this,uri);
seekBar.setMax(mediaPlayer.getDuration());
mediaPlayer.start();
max=mediaPlayer.getDuration();
play.setBackgroundResource(R.drawable.ic_pause);
Thread thread=new Thread(){
#Override
public void run() {
super.run();
int currentposition=0;
while (currentposition<max)
{
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
currentposition=mediaPlayer.getCurrentPosition();
seekBar.setProgress(currentposition);
}
}
};
thread.start();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seekBar.getProgress());
}
});
next.setOnClickListener(Musicplay.this);
play.setOnClickListener(Musicplay.this);
previous.setOnClickListener(Musicplay.this);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
mp.reset();
if(position<(Musiclist.songname.size()-1)){
position=position +1;
}
else
{
position=0;
}
uri = Uri.parse(String.valueOf(new File(Musiclist.songpath.get(position))));
try {
mp.setDataSource(Musicplay.this,uri);
} catch (IOException e) {
e.printStackTrace();
}
songmar.setText(Musiclist.songname.get(position));
songmar.setSelected(true);
try {
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
seekBar.setMax(mp.getDuration());
max=mp.getDuration();
Log.d("seekvalue",String.valueOf(max));
}
});
}
#Override
public void onClick(View v) {
idr=v.getId();
Thread thread2=new Thread(){
#Override
public void run() {
super.run();
handler.post(new Runnable() {
#Override
public void run() {
switch (idr){
case R.id.pause:
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
play.setBackgroundResource(R.drawable.ic_play);
}
else {
play.setBackgroundResource(R.drawable.ic_pause);
mediaPlayer.start();
}
break;
case R.id.next:
mediaPlayer.stop();
mediaPlayer.reset();
if(position<(Musiclist.songname.size()-1)){
position=position +1;
Uri uri=Uri.parse(String.valueOf(new File(Musiclist.songpath.get(position))));
try {
mediaPlayer.setDataSource(Musicplay.this,uri);
} catch (IOException e) {
e.printStackTrace();
}
int a=0;
for(int i=0;i<150;i++)
{
a=a+1;
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
play.setBackgroundResource(R.drawable.ic_pause);
songmar.setText(Musiclist.songname.get(position));
songmar.setSelected(true);
}
else {
position=0;
Uri uri=Uri.parse(String.valueOf(new File(Musiclist.songpath.get(position))));
try {
mediaPlayer.setDataSource(Musicplay.this,uri);
} catch (IOException e) {
e.printStackTrace();
}
int a=0;
for(int i=0;i<150;i++)
{
a=a+1;
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
play.setBackgroundResource(R.drawable.ic_pause);
songmar.setText(Musiclist.songname.get(position));
songmar.setSelected(true);
}
break;
case R.id.previous:
mediaPlayer.stop();
mediaPlayer.reset();
if(position>0){
position=position-1;
Uri uri=Uri.parse(String.valueOf(new File(Musiclist.songpath.get(position))));
try {
mediaPlayer.setDataSource(Musicplay.this,uri);
} catch (IOException e) {
e.printStackTrace();
}
int a=0;
for(int i=0;i<150;i++)
{
a=a+1;
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
play.setBackgroundResource(R.drawable.ic_pause);
songmar.setText(Musiclist.songname.get(position));
songmar.setSelected(true);
}
else {
position=Musiclist.songname.size()-1;
Uri uri=Uri.parse(String.valueOf(new File(Musiclist.songpath.get(position))));
try {
mediaPlayer.setDataSource(Musicplay.this,uri);
} catch (IOException e) {
e.printStackTrace();
}
int a=0;
for(int i=0;i<150;i++)
{
a=a+1;
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
play.setBackgroundResource(R.drawable.ic_pause);
songmar.setText(Musiclist.songname.get(position));
songmar.setSelected(true);
}
break;
}
}
});
}
};
thread2.start();
}
}
so do suggest reason why this error is taking place, and it is playing two or multiple song simultaneously.
all you have to do is, just declare mediaplayer variable public static and when you start activity to play song just check for media player is null or not and then release it

Glitch while changing video inside media player

My requirement is to change video inside video player with animation. When a person taps on "change" button the video in media player will get change with a new one and the old will end up with zoom in animation. I am able to implement this functionality with the help of texture view but I am getting one issue that there is a glitch while changing the video. is there any way I can make it more smooth?
Here is my code :
public class VideoVieww extends Activity implements TextureView.SurfaceTextureListener {
private TextureView textureView;
private MediaPlayer mMediaPlayer;
private Button mButton;
private Animation zoomAnimation;
private SurfaceTexture mSurfaceTexture;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.texture_layout);
textureView = findViewById(R.id.textureView);
textureView.setSurfaceTextureListener(this);
zoomAnimation = AnimationUtils.loadAnimation(VideoVieww.this, R.anim.zomm_out);
mButton = findViewById(R.id.change);
mButton.setOnClickListener(view -> {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
textureView.startAnimation(zoomAnimation);
try {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(VideoVieww.this, Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.broadchurch));
} catch (IOException e) {
e.printStackTrace();
}
try {
Surface surface = new Surface(mSurfaceTexture);
mMediaPlayer.setSurface(surface);
mMediaPlayer.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
});
zoomAnimation.setAnimationListener(new Animation.AnimationListener(){
#Override
public void onAnimationStart(Animation arg0) {
}
#Override
public void onAnimationRepeat(Animation arg0) {
}
#Override
public void onAnimationEnd(Animation arg0) {
mMediaPlayer.start();
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
mMediaPlayer.release();
mMediaPlayer=null;
}
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
mSurfaceTexture=surfaceTexture;
Surface surface = new Surface(surfaceTexture);
try {
mMediaPlayer= new MediaPlayer();
mMediaPlayer.setDataSource(VideoVieww.this, Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sid));
mMediaPlayer.setSurface(surface);
mMediaPlayer.prepare();
mMediaPlayer.start();
// mMediaPlayer.setLooping(true);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
}
Any help would be greatly appreciated!!!

Android app crashes in 5.0 and above when using MediaPlayer with url

I am developing an android app which play a mp3 songs by using a remote url. everything is working fine in android devices below api 5.0.But when starting app in samsung s5(5.1) it suddenly crashes
mu logcat is giving error "QCmediaPlayer mediaplayer is not present.Here is my code of Media Player
public class MainActivity2 extends Activity implements OnClickListener, OnPreparedListener {
private ProgressBar playSeekBar;
private final static String RADIO_STATION_URL ="https://aryaradio.s3.amazonaws.com/";
private String KEYNAME,encodedurl;
private List<String> playlistarray;
private List<MediaPlayer> mplayerList;
private ImageButton buttonPlay;
private List<S3ObjectSummary> playlist=null;
private ImageButton buttonStopPlay;
ProgressDialog progress;
URL url,currentsongurl;
private MediaPlayer player;
private AmazonS3Client mClient;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
playlistarray=new ArrayList<String>();
mplayerList=new ArrayList<MediaPlayer>();
if(isNetworkAvailable()) {
mClient = Util.getS3Client(MainActivity2.this);
initializeUIElements();
//new RefreshTask().execute();
buttonStopPlay.setVisibility(View.INVISIBLE);
} else {
new AlertDialog.Builder(MainActivity2.this)
.setTitle(getResources().getString(R.string.app_name))
.setMessage(
getResources().getString(
R.string.internet_error))
.setPositiveButton("OK", null).show();
buttonStopPlay.setVisibility(View.INVISIBLE);
buttonPlay.setVisibility(View.INVISIBLE);
}
}
private void initializeUIElements() {
buttonPlay = (ImageButton) findViewById(R.id.Play);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (ImageButton) findViewById(R.id.Stop);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
finish();
startActivity(new Intent(MainActivity2.this, MainActivity2.class));
}
}
private void startPlaying() {
buttonPlay.setVisibility(View.INVISIBLE);
buttonStopPlay.setVisibility(View.VISIBLE);
progress = new ProgressDialog(this);
progress.setTitle("Message");
progress.setMessage("Loading Song ...");
progress.setCancelable(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.show();
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
progress.dismiss();
player.start();
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
try {
// player.setNextMediaPlayer(mplayerList.get(2));
stopPlaying();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
});
}
private void stopPlaying() {
killMediaPlayer();
initializeMediaPlayer(playlistarray);
buttonPlay.setVisibility(View.VISIBLE);
buttonStopPlay.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer(List<String> playlist) {
player = new MediaPlayer();
int noOfSongs=playlist.size();
String url = "https://aryaradio.s3.amazonaws.com/us-east-1:eb604ac1-c4e3-4226-bea8-22f214a6b0b0/RecordingArya-9459.mp3.null";
try {
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(url);
player.setOnPreparedListener(this);
player.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
return false;
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.i("Buffering", "" + percent);
}
});
}
}

How to Play the online streaming radio in Android

I am developing one application where i want to play live stream radio. I have an url using which i will stream the radio and play. I have a play button by clicking which i want to play the radio. For that, i have written some code which is not at all working. Here is my code:
mp = new MediaPlayer();
try {
mp.setOnPreparedListener(this);
Log.d("Testing", "start111");
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
String url="xxxxxx";
mp.setDataSource(url);
mp.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
Log.d("Testing", "Exception ::: 1111 "+e.getMessage());
} catch (IllegalStateException e) {
Log.d("Testing", "Exception ::: 2222 "+e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.d("Testing", "IOException ::: 3333 "+e.getMessage());
e.printStackTrace();
}
Can anyone please help me??
You can find good information regarding radio streaming.
Github radio streaming example
and also there is a question in SOF which can also be helpful
Stackoverflow radio streaming example
Hope it will help. thanks
Try this.
public class RadioStream extends Activity {
private final static String stream = "http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio2_mf_p";
Button play;
MediaPlayer mediaPlayer;
boolean started = false;
boolean prepared = false;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio_stream);
play = (Button) findViewById(R.id.play);
play.setEnabled(false);
play.setText("Loading..");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (started) {
mediaPlayer.pause();
started = false;
play.setText("Play");
} else {
mediaPlayer.start();
started = true;
play.setText("Pause");
}
}
});
new PlayTask().execute(stream);
}
#Override
protected void onPause() {
super.onPause();
/* if(started)
mediaPlayer.pause();*/
}
#Override
protected void onResume() {
super.onResume();
/*if(started)
mediaPlayer.start();*/
}
#Override
protected void onDestroy() {
super.onDestroy();
// mediaPlayer.release();
}
private class PlayTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
play.setEnabled(true);
play.setText("Play");
}
}
}
Please do try the code below and call the given method at the on create of your activity or at the onclick listener of your button. Remember to handle the stop and start button the imgV is an imageView for my button.
private MediaPlayer player;
private void startMediaPlayer() {
String url = "http:yoururl.com"; // your URL here
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(isPlaying){
try {
mediaPlayer.prepareAsync();
progress.setVisibility(View.VISIBLE);
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
}
mediaPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
}
});
}
boolean isPlaying = true;
private void startPlaying() {
isPlaying = true;
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
imgV.setImageResource(R.drawable.stop);
}
private void stopPlaying() {
if (mediaPlayer.isPlaying()) {
isPlaying = false;
mediaPlayer.stop();
mediaPlayer.release();
initializeMediaPlayer();
}
imgV.setImageResource(R.drawable.play);
}

Android: Stop sound files playing at once

In the application I am currently writing, a user is able to select an entry from the database and play the contents of that entry: an entry is made up of a number of sound files (without a limit). In my application, I return the URI locations of the sound files of an entry (which have been stored in my database) in a List. The code is as follows:
public void audioPlayer() {
// set up MediaPlayer
MediaPlayer mp = new MediaPlayer();
DatabaseHandler db = new DatabaseHandler(this);
Entry retrieveEntry = new Entry();
retrieveEntry = db.getEntry();
List<String> path = retrieveEntry.getAudioUri();
path.size();
System.out.println("PATH SIZE: " +path.size());
System.out.println("FILEZ: " + path);
Iterator<String> i = path.iterator();
String myAudio;
int count = 0;
while (i.hasNext()) {
System.out.println(count);
myAudio = i.next();
System.out.println("MY AUDIO: " + myAudio);
MediaPlayer player = MediaPlayer.create(this, Uri.parse(myAudio));
player.start();
player.stop();
player = MediaPlayer.create(this, Uri.parse(myAudio));
player.start();
count++;
}
}
My users require that there be user input for playing a file - is there a way to play the first file, then wait for the user to press the button, then play the second file, then wait for the user to press the button, etc.? At the moment, when the play button is pressed, all of the sound files that have been returned get played at the same time, rather than one after the other.
Thanks in advance for any help provided!
You can use this class to play a playlist. This will start one audio, when that audio finishes, it will start playing next audio till the end of the list. If you want to play the playlist in looping i.e start first audio after reaching end, then pass isLooping=true in startPlayingPlaylist(list,looping)
AudioPlayer player = new AudioPlayer();
player.startPlayingPlaylist(list, false);
Class
public class AudioPlayer{
MediaPlayer player = null;
ArrayList<String> playlist = null;
int position = 0;
public AudioPlayer() {
super();
// TODO Auto-generated constructor stub
}
public void startPlayingPlaylist(ArrayList<String> list, boolean looping){
playlist = list;
if(player!=null){
player.release();
}
if(playlist!=null && playlist.size()>0){
player = MediaPlayer.create(LMApplicaton.getInstance(),Uri.parse(playlist.get(position)));
player.setWakeMode(LMApplicaton.getInstance(), PowerManager.PARTIAL_WAKE_LOCK);
player.setLooping(looping);
player.start();
// Set onCompletion listener
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
position = position+1;
if(position<playlist.size()){
try {
player.reset();
player.setDataSource(playlist.get(position));
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if(player.isLooping()==true){
position = position%playlist.size();
try {
player.reset();
player.setDataSource(playlist.get(position));
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(player.isLooping()==false){
player.release();
player = null;
}
}
});
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
}
public void pause(){
if(player!=null && player.isPlaying()){
player.pause();
}
}
public void play(){
if(player!=null && player.isPlaying()==false){
player.start();
}
}
public boolean isPlaying(){
return player.isPlaying();
}
public void release(){
if(player!=null){
player.release();
}
}
}
Edit:
The class below receives a list of audios, then plays first Audio. It plays next audio when user calls startNextAudio() You can use any one of these according to your requirements
public class AudioPlayer{
MediaPlayer player = null;
ArrayList playlist = null;
int position = 0;
public AudioPlayer() {
super();
// TODO Auto-generated constructor stub
}
public void startPlayingPlaylist(ArrayList<String> list){
playlist = list;
if(player!=null){
player.release();
}
if(playlist!=null && playlist.size()>0){
player = MediaPlayer.create(LMApplicaton.getInstance(),Uri.parse(playlist.get(position)));
player.setWakeMode(LMApplicaton.getInstance(), PowerManager.PARTIAL_WAKE_LOCK);
player.start();
// Set onCompletion listener
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
}
public void startNextAudio(){
position = position+1;
if(position<playlist.size()){
try {
player.reset();
player.setDataSource(playlist.get(position));
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if(player.isLooping()==true){
position = position%playlist.size();
try {
player.reset();
player.setDataSource(playlist.get(position));
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
Log.i("AudioPlayer","Playlist reached at the end");
}
}
public void pause(){
if(player!=null && player.isPlaying()){
player.pause();
}
}
public void play(){
if(player!=null && player.isPlaying()==false){
player.start();
}
}
public boolean isPlaying(){
return player.isPlaying();
}
public void release(){
if(player!=null){
player.release();
}
}
}
One approach would be to implement the MediaPlayer.OnCompletionListener interface. This gives you the MediaPlayer.onCompletion() callback method which you could use like so:
#Override
public void onCompletion(MediaPlayer mp) {
if (i.hasNext) {
// ...hand mp the next file
// ...show the user the 'play next' button
}
}
Note you also will need to call the MediaPlayer.setOnCompletionListener() method in your setup.

Categories

Resources