I have radio app which streams online radio. But it don't work on background i.e when i press home button phone automatically shut it down. how do i make it run on background.
package com.radioawaz.simerpreetjassal.radioawaz;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import java.io.IOException;
public class MainActivity extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
Log.e("ready!","ready");
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("http://streaming.shoutcast.com/Radioawazca?lang=en-ca");
} 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) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
All above is my main Activity. please look and give suggestion.Thanks in advance.
Related
I have an activity named Player Activity in which I am streaming music with the help of MediaPlayer API. Whenever my activity is created a notification is displayed which has some basic control of the music player.
So when I tap on my notification it jumps back to the Player Activity, but the state of the activity is lost.
Before tapping on notification :
After tapping on notification :
Here is the code of my notification's Pending Intent
Intent notifyIntent = new Intent(context, PlayerActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
notifyIntent.setAction("android.intent.action.MAIN");
notifyIntent.addCategory("android.intent.category.LAUNCHER");
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Here is the code for PlayerActivity.java :
package com.example.user.musicplayer;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.concurrent.TimeUnit;
import de.hdodenhof.circleimageview.CircleImageView;
public class PlayerActivity extends AppCompatActivity implements MediaPlayer.OnBufferingUpdateListener,MediaPlayer.OnCompletionListener{
private static Button btn_play_pause;
private Button btnToggleRepeat;
private Button btnStop;
private SeekBar seekBar;
private TextView textView;
public static MediaPlayer mediaPlayer;
private int mediaFileLength;
private int realtimeLength;
private String musicUrl;
private String imageUrl;
final Handler handler = new Handler();
private boolean isRepeat;
private CircleImageView musicImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
Log.d("TAG", "onCreate");
NotificationGenerator.customBigNotification(getApplicationContext());
musicUrl = getIntent().getStringExtra("musicUrl");
imageUrl = getIntent().getStringExtra("imageUrl");
seekBar = (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 = (mediaFileLength/100)*seekBar.getProgress();
mediaPlayer.seekTo(playPosition);
}
return false;
}
});
textView = (TextView)findViewById(R.id.txtTime);
btnToggleRepeat = findViewById(R.id.btnRepeat);
btnStop = findViewById(R.id.btnStop);
musicImage = findViewById(R.id.musicImgView);
Picasso.get().load(imageUrl).placeholder(R.drawable.music).error(R.drawable.music).into(musicImage);
btn_play_pause = (Button) findViewById(R.id.btnTogglePlay);
btn_play_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog mDialog = new ProgressDialog(PlayerActivity.this);
AsyncTask<String,String,String> mp3Play = new AsyncTask<String, String, String>() {
#Override
protected void onPreExecute() {
mDialog.setMessage("Please wait");
mDialog.show();
}
#Override
protected String doInBackground(String... params) {
try{
mediaPlayer.setDataSource(params[0]);
mediaPlayer.prepare();
}
catch (Exception ex)
{
}
return "";
}
#Override
protected void onPostExecute(String s) {
mediaFileLength = mediaPlayer.getDuration();
realtimeLength = mediaFileLength;
if(!mediaPlayer.isPlaying())
{
playMusic();
}
else
{
pauseMusic();
}
updateSeekBar();
mDialog.dismiss();
}
};
mp3Play.execute(musicUrl); // direct link mp3 file
}
});
btnToggleRepeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isRepeat){
isRepeat = false;
mediaPlayer.setLooping(false);
btnToggleRepeat.setText("Repeat");
}
else{
isRepeat = true;
mediaPlayer.setLooping(true);
btnToggleRepeat.setText("Single");
}
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mediaPlayer.pause();
mediaPlayer.stop();
}
catch (Exception e){
Toast.makeText(PlayerActivity.this, "Opps! sorry something bad happened", Toast.LENGTH_SHORT).show();
}
}
});
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
public void pauseMusic() {
mediaPlayer.pause();
btn_play_pause.setText("Play");
}
public void playMusic() {
mediaPlayer.start();
btn_play_pause.setText("Pause");
}
private void updateSeekBar() {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / mediaFileLength)*100));
if(mediaPlayer.isPlaying())
{
Runnable updater = new Runnable() {
#Override
public void run() {
updateSeekBar();
realtimeLength-=1000; // declare 1 second
textView.setText(String.format("%d:%d",TimeUnit.MILLISECONDS.toMinutes(realtimeLength),
TimeUnit.MILLISECONDS.toSeconds(realtimeLength) -
TimeUnit.MILLISECONDS.toSeconds(TimeUnit.MILLISECONDS.toMinutes(realtimeLength))));
}
};
handler.postDelayed(updater,1000); // 1 second
}
}
#Override
protected void onResume() {
super.onResume();
Log.d("TAG", "onResume");
}
#Override
protected void onStart() {
super.onStart();
Log.d("TAG", "onStart");
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
if(!mediaPlayer.isLooping())
btn_play_pause.setText("Play");
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onPause() {
super.onPause();
}
public static class DownloadCancelReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("notificationPlayer","Received Cancelled Event");
}
}
}
Thanks in advance. Pardon me if the explanation is not clear, because if i might have right words to explain it, I would have googled it.
Add this to your PlayerActivity activity in manifest :
android:launchMode="singleTask"
And use these flags in the intent for pendingintent :
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
**Down here I am trying to build a music app in android studio,my app is working fine displaying all my SD card songs and play too ,all button works but when I click on next button it works normally but don't know why app sometimes gets stopped working and shows runtime exception ->>please open the image of run log of the application.
package com.example.ramandeepsingh.tunes;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.jar.Manifest;
public class PlayerActivity extends AppCompatActivity{
static MediaPlayer mp;//assigning memory loc once or else multiple songs will play at once
int position;
SeekBar sb;
ArrayList<File> mySongs;
Thread updateSeekBar;
Button pause,forward,reverse,next,previous;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
pause = (Button)findViewById(R.id.pause);
forward = (Button)findViewById(R.id.forward);
previous = (Button)findViewById(R.id.previous);
next = (Button)findViewById(R.id.next);
reverse = (Button)findViewById(R.id.reverse);
sb=(SeekBar)findViewById(R.id.seekBar);
updateSeekBar=new Thread(){
#Override
public void run(){
int totalDuration = mp.getDuration();
int currentPosition = 0;
// sb.setMax(totalDuration);
while(currentPosition < totalDuration){
try{
sleep(500);
currentPosition=mp.getCurrentPosition();
}
catch (InterruptedException e){
e.printStackTrace();
System.out.println(e);
}
sb.setProgress(currentPosition);
}
}
};
if(mp != null){
mp.stop();
mp.release();
}
Intent i = getIntent();
Bundle b = i.getExtras();
mySongs = (ArrayList) b.getParcelableArrayList("songs");
position = b.getInt("pos",0);
Uri u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(),u);
mp.start();
sb.setMax(mp.getDuration());
updateSeekBar.start();
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mp.seekTo(seekBar.getProgress());
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sb.setMax(mp.getDuration());
if(mp.isPlaying()){
pause.setText(">");
mp.pause();
}
else {
pause.setText("||");
mp.start();
}
}
});
forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sb.setMax(mp.getDuration());
mp.seekTo(mp.getCurrentPosition()+5000);
}
});
reverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sb.setMax(mp.getDuration());
mp.seekTo(mp.getCurrentPosition()-5000);
}
});
next.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
mp.reset();
position=((position+1)%mySongs.size());
Uri u = Uri.parse(mySongs.get( position).toString());
mp = MediaPlayer.create(getApplicationContext(),u);
mp.start();
sb.setMax(mp.getDuration());
updateSeekBar.start();
}
});
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
mp.release();
position=((position-1)<0)?(mySongs.size()-1):(position-1);
Uri u = Uri.parse(mySongs.get( position).toString());//%mysongs so that it do not go to invalid position
mp = MediaPlayer.create(getApplicationContext(),u);
mp.start();
}
});
}}
I have implemented the Player and now there is a problem. When the video is playing and if the app is closed and resumed, the video screen freezes. I even saw the ExoPlayer Demo Activity from Google for better understanding but I could not get through it for implementing in my app. I have attached the Player Activity here and for the full code, I am sharing the GitHub repository for all files.
RecipeStepDetailFragment.java
package com.example.android.recipe.ui;
import android.content.Context;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.recipe.R;
import com.example.android.recipe.pojo.Recipe;
import com.example.android.recipe.pojo.Step;
import com.google.android.exoplayer2.LoadControl;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import java.util.ArrayList;
import java.util.List;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveVideoTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import com.squareup.picasso.Picasso;
import static com.example.android.recipe.ui.RecipeActivity.SELECTED_INDEX;
import static com.example.android.recipe.ui.RecipeActivity.SELECTED_RECIPES;
import static com.example.android.recipe.ui.RecipeActivity.SELECTED_STEPS;
public class RecipeStepDetailFragment extends Fragment {
private SimpleExoPlayerView simpleExoPlayerView;
private SimpleExoPlayer player;
private BandwidthMeter bandwidthMeter;
private ArrayList<Step> steps = new ArrayList<>();
private int selectedIndex;
private Handler mainHandler;
ArrayList<Recipe> recipe;
String recipeName;
public RecipeStepDetailFragment() { }
private ListItemClickListener itemClickListener;
public interface ListItemClickListener {
void onListItemClick(List<Step> allSteps,int Index,String recipeName);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
TextView textView;
mainHandler = new Handler();
bandwidthMeter = new DefaultBandwidthMeter();
itemClickListener =(RecipeDetailActivity)getActivity();
recipe = new ArrayList<>();
if(savedInstanceState != null) {
steps = savedInstanceState.getParcelableArrayList(SELECTED_STEPS);
selectedIndex = savedInstanceState.getInt(SELECTED_INDEX);
recipeName = savedInstanceState.getString("Title");
}
else {
steps =getArguments().getParcelableArrayList(SELECTED_STEPS);
if (steps!=null) {
steps =getArguments().getParcelableArrayList(SELECTED_STEPS);
selectedIndex=getArguments().getInt(SELECTED_INDEX);
recipeName=getArguments().getString("Title");
}
else {
recipe =getArguments().getParcelableArrayList(SELECTED_RECIPES);
steps=(ArrayList<Step>)recipe.get(0).getSteps();
selectedIndex=0;
}
}
View rootView = inflater.inflate(R.layout.recipe_step_detail_fragment_body_part, container, false);
textView = (TextView) rootView.findViewById(R.id.recipe_step_detail_text);
textView.setText(steps.get(selectedIndex).getDescription());
textView.setVisibility(View.VISIBLE);
simpleExoPlayerView = (SimpleExoPlayerView) rootView.findViewById(R.id.playerView);
simpleExoPlayerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
String videoURL = steps.get(selectedIndex).getVideoURL();
if (rootView.findViewWithTag("sw600dp-port-recipe_step_detail")!=null) {
recipeName=((RecipeDetailActivity) getActivity()).recipeName;
((RecipeDetailActivity) getActivity()).getSupportActionBar().setTitle(recipeName);
}
String imageUrl=steps.get(selectedIndex).getThumbnailURL();
if (imageUrl!="") {
Uri builtUri = Uri.parse(imageUrl).buildUpon().build();
ImageView thumbImage = (ImageView) rootView.findViewById(R.id.thumbImage);
Picasso.with(getContext()).load(builtUri).into(thumbImage);
}
if (!videoURL.isEmpty()) {
initializePlayer(Uri.parse(steps.get(selectedIndex).getVideoURL()));
if (rootView.findViewWithTag("sw600dp-land-recipe_step_detail")!=null) {
getActivity().findViewById(R.id.fragment_container2).setLayoutParams(new LinearLayout.LayoutParams(-1,-2));
simpleExoPlayerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIXED_WIDTH);
}
else if (isInLandscapeMode(getContext())){
textView.setVisibility(View.GONE);
}
}
else {
player=null;
simpleExoPlayerView.setForeground(ContextCompat.getDrawable(getContext(), R.drawable.ic_visibility_off_white_36dp));
simpleExoPlayerView.setLayoutParams(new LinearLayout.LayoutParams(300, 300));
}
Button mPrevStep = (Button) rootView.findViewById(R.id.previousStep);
Button mNextstep = (Button) rootView.findViewById(R.id.nextStep);
mPrevStep.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (steps.get(selectedIndex).getId() > 0) {
if (player!=null){
player.stop();
}
itemClickListener.onListItemClick(steps,steps.get(selectedIndex).getId() - 1,recipeName);
}
else {
Toast.makeText(getActivity(),"You already are in the First step of the recipe", Toast.LENGTH_SHORT).show();
}
}});
mNextstep.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int lastIndex = steps.size()-1;
if (steps.get(selectedIndex).getId() < steps.get(lastIndex).getId()) {
if (player!=null){
player.stop();
}
itemClickListener.onListItemClick(steps,steps.get(selectedIndex).getId() + 1,recipeName);
}
else {
Toast.makeText(getContext(),"You already are in the Last step of the recipe", Toast.LENGTH_SHORT).show();
}
}});
return rootView;
}
private void initializePlayer(Uri mediaUri) {
if (player == null) {
TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveVideoTrackSelection.Factory(bandwidthMeter);
DefaultTrackSelector trackSelector = new DefaultTrackSelector(mainHandler, videoTrackSelectionFactory);
LoadControl loadControl = new DefaultLoadControl();
player = ExoPlayerFactory.newSimpleInstance(getContext(), trackSelector, loadControl);
simpleExoPlayerView.setPlayer(player);
String userAgent = Util.getUserAgent(getContext(), "Baking App");
MediaSource mediaSource = new ExtractorMediaSource(mediaUri, new DefaultDataSourceFactory(getContext(), userAgent), new DefaultExtractorsFactory(), null, null);
player.prepare(mediaSource);
player.setPlayWhenReady(true);
}
}
#Override
public void onSaveInstanceState(Bundle currentState) {
super.onSaveInstanceState(currentState);
currentState.putParcelableArrayList(SELECTED_STEPS,steps);
currentState.putInt(SELECTED_INDEX,selectedIndex);
currentState.putString("Title",recipeName);
}
public boolean isInLandscapeMode( Context context ) {
return (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE);
}
#Override
public void onDetach() {
super.onDetach();
if (player!=null) {
player.stop();
player.release();
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (player!=null) {
player.stop();
player.release();
player=null;
}
}
#Override
public void onStop() {
super.onStop();
if (player!=null) {
player.stop();
player.release();
}
}
#Override
public void onPause() {
super.onPause();
if (player!=null) {
player.stop();
player.release();
}
}
}
Complete Project Repository: https://github.com/mtp2697/Udacity-AndroidDeveloperNanodegree-BakingApp
Help with the restoring of the state of video player for onPause() and onResume()
Thanks,
Praveen Thirumurugan.
I faced the same problem in my submission for the baking app and I did something like this:
private void initPlayer() {
// Exoplayer
// 1. Create a default TrackSelector
// Handler mainHandler = new Handler();
videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
RenderersFactory render = new DefaultRenderersFactory(getContext());
mainHandler = new Handler();
if (CookieHandler.getDefault() != DEFAULT_COOKIE_MANAGER) {
CookieHandler.setDefault(DEFAULT_COOKIE_MANAGER);
}
// 2. Create a default LoadControl
LoadControl loadControl = new DefaultLoadControl();
// 3. Create the player
recipeVideoPlayer = ExoPlayerFactory.newSimpleInstance(render, trackSelector, loadControl);
// exoPlayerView = (SimpleExoPlayerView) v.findViewById(R.id.exoplayer_recipe);
// Set media controller
mExoplayer.setUseController(true);
mExoplayer.setControllerVisibilityListener(this);
mExoplayer.requestFocus();
// Bind the player to the view.
mExoplayer.setPlayer(recipeVideoPlayer);
if (TextUtils.isEmpty(mSteps.getVideoURL())) {
mExoplayer.setVisibility(View.GONE);
} else {
mExoplayer.setVisibility(View.VISIBLE);
Uri video = Uri.parse(mSteps.getVideoURL());
DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(getContext(), Util.getUserAgent(getContext(), "recipes"), null);
ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
MediaSource videoSource = new ExtractorMediaSource(video, dataSourceFactory, extractorsFactory, mainHandler, null);
boolean haveResumePosition = resumeWindow != C.INDEX_UNSET;
if (haveResumePosition) {
recipeVideoPlayer.seekTo(resumeWindow, resumePosition);
}
recipeVideoPlayer.prepare(videoSource, !haveResumePosition, false);
recipeVideoPlayer.setPlayWhenReady(true);
recipeVideoPlayer.addListener(new ExoPlayer.EventListener() {
#Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
// Toast.makeText(getContext(), "Track changed" + trackSelections.length, Toast.LENGTH_SHORT).show();
//
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
clearResumePosition();
}
#Override
public void onPositionDiscontinuity() {
// updateResumePosition();
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
});
}
}
private void releasePlayer() {
if (recipeVideoPlayer != null) {
updateResumePosition();
recipeVideoPlayer.stop();
recipeVideoPlayer.release();
recipeVideoPlayer = null;
}
}
#Override
public void onResume() {
super.onResume();
if (recipeVideoPlayer == null) {
initPlayer();
}
}
#Override
public void onPause() {
super.onPause();
releasePlayer();
}
you can refer my project here
I'm trying to make a sort of soundboard app in Android Studio. For now I have three buttons: 2 of them play specific audio files and the other one stops the audio. Everything works except if you play one audio file while another one is going already they both play at the same time and the stop button no longer works on either of them. You have to exit the app. I cannot figure out how to get the first file to quit before playing the second. Here is my code so far:
package com.something.example.com;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
private Button startLie, startTruth,
stopScan;
private MediaPlayer play;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startLie = (Button) findViewById(R.id.startlie);
startLie.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
play = MediaPlayer.create(MainActivity.this, R.raw.lie_detector);
play.start();
play.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer play) {
play.release();
}
});
}
});
stopScan = (Button) findViewById(R.id.stopScan);
stopScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
play.stop();
};
});
startTruth = (Button) findViewById(R.id.starttruth);
startTruth.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
play = MediaPlayer.create(MainActivity.this, R.raw.truth_detector);
play.start();
play.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer play) {
play.release();
}
});
}
});
So I seem to have been able to finally get this to work. I basically created a stopPlaying function (placed at the end of my file. and then called it every time before the audio files play. Here's the code again, and this time with a couple more buttons.
package com.something.example;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
private Button startLie, startTruth,
startIdiot, startGenius, stopScan;
private MediaPlayer play;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startLie = (Button) findViewById(R.id.startlie);
startLie.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
play = MediaPlayer.create(MainActivity.this, R.raw.lie_detector);
play.start();
play.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer play) {
play.release();
}
});
}
});
stopScan = (Button) findViewById(R.id.stopScan);
stopScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
play.stop();
};
});
startTruth = (Button) findViewById(R.id.starttruth);
startTruth.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
play = MediaPlayer.create(MainActivity.this, R.raw.truth_detector);
play.start();
play.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer play) {
play.release();
}
});
}
});
startIdiot = (Button) findViewById(R.id.startidiot);
startIdiot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
play = MediaPlayer.create(MainActivity.this, R.raw.idiot_detector);
play.start();
play.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer play) {
play.release();
}
});
}
});
startGenius = (Button) findViewById(R.id.startgenius);
startGenius.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
play = MediaPlayer.create(MainActivity.this, R.raw.genius_detector);
play.start();
play.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer play) {
play.release();
}
});
}
});
}
private void stopPlaying() {
if (play != null) {
play.stop();
play.release();
play = null;
}
}
The "stop" and "play" work fine, but "pause" works like "stop". When I press pause, the audiofile stops playing and when I press play, it starts from the beginning.
The "stop" and "play" work fine, but "pause" works like "stop". When I press pause, the audiofile stops playing and when I press play, it starts from the beginning.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class HelloMoonFragment extends Fragment
{
private AudioPlayer mPlayer = new AudioPlayer();
private Button mPlayButton;
private Button mStopButton;
private Button mPauseButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_hello_moon, parent, false);
mPlayButton = (Button)v.findViewById(R.id.hellomoon_playButton);
mPlayButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
mPlayer.play(getActivity());
}
});
mPauseButton = (Button) v.findViewById(R.id.hellomoon_pauseButton);
mPauseButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
mPlayer.pause();
}
});
mStopButton = (Button)v.findViewById(R.id.hellomoon_stopButton);
mStopButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
mPlayer.stop();
}
});
return v;
}
#Override
public void onDestroy()
{
super.onDestroy();
mPlayer.stop();
}
}
package com.example.hellomoon;
import android.content.Context;
import android.media.MediaPlayer;
public class AudioPlayer {
private MediaPlayer mPlayer;
public void stop()
{
if(mPlayer != null)
{
mPlayer.release();
mPlayer = null;
}
}
public void pause()
{
if(mPlayer.isPlaying())
{
mPlayer.pause();
}
}
public void play(Context c)
{
stop();
mPlayer = MediaPlayer.create(c, R.raw.one_small_step);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
stop();
}
});
mPlayer.start();
}
}
it starts from the beginning because here:
public void play(Context c) {
stop();
mPlayer = MediaPlayer.create(c, R.raw.one_small_step);
you are releasing the old one a create it again
Try remembering the the player is paused:
public class AudioPlayer {
boolean isPaused = false;
public void pause() {
if(mPlayer.isPlaying()) {
mPlayer.pause();
isPaused = true;
}
}
public void play(Context c) {
if (isPaused && mPlayer != null) {
mPlayer.start();
isPaused = false
return;
}
stop();
mPlayer = MediaPlayer.create(c, R.raw.one_small_step);