I have seen a few tutorials that indicate that in order to play the next song from a raw folder all I need to do is write some code like:
case R.id.next : mp.next();break;"
However it is not working. What is the right way to implement the "play previous and play next song"?
Here is my code for reference:
public class MainActivity extends Activity implements OnClickListener, OnPreparedListener{
private static final String SAVE_POSITION = "MainActivity.SAVE_POSITION";
public static final int STANDARD_NOTIFICATION = 0x01001;
public static final int EXPANDED_NOTIFICATION = 0x01002;
private static final int REQUEST_NOTIFY_LAUNCH = 0;
//Audio Control buttons
Button media;
Button pause;
Button stop;
Button prev;
Button next;
//Media Player
MediaPlayer mp;
boolean mActivityResumed;
boolean mPrepared;
int mAudioPosition;
//array of songs
private int[] rawFiles = {R.raw.black_banquet,R.raw.door_of_holy_spirits,R.raw.castlevania_prologue};
//random playback
private Random random = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPrepared = mActivityResumed = false;
mAudioPosition = 0;
if(savedInstanceState != null && savedInstanceState.containsKey(SAVE_POSITION)) {
mAudioPosition = savedInstanceState.getInt(SAVE_POSITION, 0);
}
//button audio playback control
media = (Button) findViewById(R.id.btMedia);
media.setOnClickListener(this);
pause = (Button) findViewById(R.id.pause);
pause.setOnClickListener(this);
stop = (Button) findViewById(R.id.stop);
stop.setOnClickListener(this);
media = (Button) findViewById(R.id.prev);
media.setOnClickListener(this);
media = (Button) findViewById(R.id.next);
media.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.btMedia: if (mp == null){
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
//random song
mp = MediaPlayer.create(this, rawFiles[random.nextInt(rawFiles.length)]);
}
//looping one song
mp.setLooping(true);
mp.start();
break;
case R.id.pause : mp.pause();break;
case R.id.next : mp.next();break;
case R.id.stop : mp.stop();mp = null;break;
}
// Notification Manager
NotificationManager mgr =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
// Setting the default action.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pIntent =
PendingIntent.getActivity(this, REQUEST_NOTIFY_LAUNCH, intent, 0);
// Setting the default action.
builder.setContentIntent(pIntent);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setLargeIcon(BitmapFactory.decodeResource(
getResources(), R.drawable.ic_launcher));
builder.setContentTitle("Standard Title");
builder.setContentText("songTitle");
mgr.notify(STANDARD_NOTIFICATION, builder.build());
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(mp != null) {
outState.putInt(SAVE_POSITION, mp.getCurrentPosition());
}
}
#Override
protected void onResume() {
super.onResume();
mActivityResumed = true;
if(mp != null && !mPrepared) {
mp.prepareAsync();
} else if(mp != null && mPrepared) {
mp.seekTo(mAudioPosition);
mp.start();
}
}
#Override
protected void onPause() {
super.onPause();
mActivityResumed = false;
if(mp != null && mp.isPlaying()) {
mp.pause();
}
}
#Override
protected void onStop() {
super.onStop();
if(mp != null && mp.isPlaying()) {
mp.stop();
mPrepared = false;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if(mp != null) {
mp.release();
}
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mPrepared = true;
if(mp != null && mActivityResumed) {
mp.seekTo(mAudioPosition);
mp.start();
}
}
For the Android MediaPlayer class there is no next method. What you need to do in order to implement the next functionality is to call mp.reset(), mp.setDataSource() with the next audio file, and mp.prepare().
E.x.
case R.id.next : {
mp.reset();
mp.setDataSource(**LOCATION OF YOUR AUDIO FILE**)
//See http://developer.android.com/reference/android/media/MediaPlayer.html#setDataSource(java.lang.String)
mp.prepare();
break;
}
Related
in my app exist two activity and a button . when user touch button in activity1 , app go to activity2 that three image with sound played Consecutively and repeat until user touch back button.
when user touch back button application go to activity1 .
The problem is that when the back button is pressed, it goes to the second activity, but there is no image displayed, and the broadcast sound is not interrupted, and it is constantly repeated, and the program loop does not come out.
I do not know where the program logic is wrong!
please guide me
my code is:
{
public MediaPlayer mp = new MediaPlayer();
Button button;
ImageView im;
Context context;
int current_img = 0;
int current_aud = 0;
boolean flag= false;
int[] sounds={R.raw.anar,R.raw.ab,R.raw.abi};
int[] images = { R.drawable.anar, R.drawable.water , R.drawable.abi};
String[] texts={"انار","آب","آبی"};
AnimationDrawable animation = new AnimationDrawable();
#Override
public void onBackPressed() {
if (mp != null && mp.isPlaying()) {
Toast.makeText(MainActivity.this, "in backpress", Toast.LENGTH_LONG).show();
mp.stop();
mp.release();
mp = null;
super.onBackPressed();
this.finish();
}
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView=findViewById(R.id.textView);
im = findViewById(R.id.imageView);
im.setImageResource(R.drawable.anar);
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
int i = 0;
int j = 0;
public void run()
{
textView.setText(texts[i]);
im.setImageResource(images[i]);
i++;
mp = MediaPlayer.create(MainActivity.this, sounds[j]);
Toast.makeText(MainActivity.this, "in while", Toast.LENGTH_LONG).show();
mp.start();
j++;
if (j > sounds.length - 1) {
j = 0;
}
if (i > images.length - 1) {
i = 0;
}
handler.postDelayed(this, 5000); //for interval...
}
};
}
}
move the handler to class , and release it in onBackPressed()
try to change the onBackPressed():
final Handler handler = new Handler();
#Override
public void onBackPressed() {
Toast.makeText(this, "in backpress", Toast.LENGTH_LONG).show();
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
if(handler!=null){
handler.removeCallbacksAndMessages(null);
}
super.onBackPressed();
}
I'm trying to using Cleveroad WaveInApp in my Application
https://github.com/Cleveroad/WaveInApp everything is working fine as I want but when Song Completed it also stops mediaPlayer.setOnCompletionListener(which works fine when I removed this code).
When I try to change the song it crashes.
Error :-
java.lang.NullPointerException: Attempt to invoke interface method 'void com.cleveroad.audiovisualization.InnerAudioVisualization.stopRendering()' on a null object reference
at com.cleveroad.audiovisualization.DbmHandler.stopRendering(DbmHandler.java:61)
at com.cleveroad.audiovisualization.DbmHandler$2.onCalmedDown(DbmHandler.java:82)
at com.cleveroad.audiovisualization.GLAudioVisualizationView$1.onCalmedDown(GLAudioVisualizationView.java:49)
at com.cleveroad.audiovisualization.GLRenderer.onDrawFrame(GLRenderer.java:87)
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1608)
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1299)
MainContainer.class
public class MainContainer extends AppCompatActivity
implements
NavigationView.OnNavigationItemSelectedListener,
SeekBar.OnSeekBarChangeListener {
private static final String LOGTAG = "Friday";
public static final String isPlay = "isPlay";
public static final String NOTIFICATION_ACTION = "Notification_Action";
private static final String VOLUME_BUTTON = "android.media.VOLUME_CHANGED_ACTION";
SlidingUpPanelLayout slideLayout;
MusicService mService;
boolean mBound = false;
Timer t = new Timer();
SeekBar seekBar;
ImageView albumArt;
ImageView panelAlbumart;
TextView songname;
TextView singername;
TextView seekCurrentDuration;
TextView seekTotalDuration;
TextView panelSongname;
TextView panelSingername;
ImageView playBtn;
IntentFilter mIntentFilter;
RelativeLayout panelHead;
SeekBar volumeControl;
AudioManager audioManager;
AudioVisualization audioVisualization;
VisualizerDbmHandler vizualizerHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_container);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setVolumeControlStream(AudioManager.STREAM_MUSIC); //best practice to set volume control
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ViewPager vp_pages = findViewById(R.id.vp_pages);
PagerAdapter pagerAdapter = new FragmentAdapter(getSupportFragmentManager());
vp_pages.setAdapter(pagerAdapter);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(isPlay);
mIntentFilter.addAction(VOLUME_BUTTON);
mIntentFilter.addAction(NOTIFICATION_ACTION);
TabLayout tbl_pages = findViewById(R.id.tbl_pages);
tbl_pages.setupWithViewPager(vp_pages);
seekBar = findViewById(R.id.seek_bar_red);
seekBar.setOnSeekBarChangeListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_container, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, MusicService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
unbindService(mConnection);
mBound = false;
}
// control Volume by Seekbar
private void volumeControl() {
volumeControl = findViewById(devil.jarvis.friday.R.id.volume_control);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (audioManager != null) {
volumeControl.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeControl.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
}
volumeControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
#Override
public void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
init();
//todo add this when song is played
audioVisualization.onResume();
updateUI();
volumeControl();
}
#Override
public void onPause() {
audioVisualization.onPause();
unregisterReceiver(mReceiver);
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
private void init() {
albumArt = findViewById(R.id.musicArt);
panelAlbumart = findViewById(R.id.slidePanelArt);
songname = findViewById(R.id.song_name);
singername = findViewById(R.id.singer_name);
panelSingername = findViewById(R.id.singer_name_head);
panelSongname = findViewById(R.id.song_name_head);
seekCurrentDuration = findViewById(R.id.current_time);
seekTotalDuration = findViewById(R.id.song_duration);
playBtn = findViewById(R.id.play);
panelHead = findViewById(R.id.header);
slideLayout = findViewById(R.id.sliding_layout);
audioVisualization = findViewById(R.id.visualizer_view);
}
public void updateUI() {
//Update UI
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (mBound) {
try {
setupMusicUI(mService.getCurrentDuration(), mService.getDuration());
} catch (Exception e) {
//
}
}
}
}, 0, 1000);
}
private void setupMusicUI(int currentDuration, int duration) {
seekBar.setMax(duration);
seekBar.setProgress(currentDuration);
}
// code for update song details
private void updateTextInfo() {
if (mBound) {
int pos = mService.getPosition();
panelSongname.setText(arrayList.get(pos));
panelSingername.setText(artistName.get(pos));
songname.setText(arrayList.get(pos));
singername.setText(artistName.get(pos));
//update album art with text also
updateAlbumArt();
changePlayBtn();
startEqualiser();
// try{
// startEqualiser();
// }catch (Exception e){
// //
// }
}
}
private void setSeekbarTime(int position, int duration) {
int curr_time_seconds = (position / 1000) % 60;
int curr_time_minutes = (position / 1000) / 60;
int dur_time_seconds = (duration / 1000) % 60;
int dur_time_minutes = (duration / 1000) / 60;
String current_zero_minutes = "0";
String current_zero_seconds = "0";
String duration_zero_minues = "0";
String duration_zero_seconds = "0";
if (curr_time_minutes > 9)
current_zero_minutes = "";
if (curr_time_seconds > 9)
current_zero_seconds = "";
if (dur_time_minutes > 9)
duration_zero_minues = "";
if (dur_time_seconds > 9)
duration_zero_seconds = "";
seekCurrentDuration.setText(current_zero_minutes + curr_time_minutes + ":" + current_zero_seconds + curr_time_seconds);
seekTotalDuration.setText(duration_zero_minues + dur_time_minutes + ":" + duration_zero_seconds + dur_time_seconds);
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(VOLUME_BUTTON)) {
volumeControl();
}
if (intent.getAction().equals(isPlay)) {
boolean show = intent.getBooleanExtra("showPanel", false);
if (show) {
//show Panel here
slideLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
updateTextInfo();
}
} else if (intent.getAction().equals(NOTIFICATION_ACTION)) {
int action = intent.getIntExtra("action", 0);
switch (action) {
case 1:
changePlayBtn();
break;
case 2:
updateTextInfo();
break;
case 3:
updateTextInfo();
break;
case 4:
audioVisualization.release();
break;
default:
break;
}
}
}
};
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
/**
* Defines callbacks for service binding, passed to bindService()
*/
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
public void playBtn(View view) {
if (mBound) {
mService.play();
changePlayBtn();
}
}
private void changePlayBtn() {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
playBtn.setImageResource(R.drawable.ic_pause_button);
} else {
playBtn.setImageResource(R.drawable.ic_play_arrow);
}
}
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
setSeekbarTime(i, mediaPlayer.getDuration());
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mService.changeSeekTo(seekBar.getProgress());
}
public void previousBtn(View view) {
if (mBound) {
mService.previous();
updateTextInfo();
}
}
public void nextBtn(View view) {
if (mBound) {
mService.next();
updateTextInfo();
}
}
public void startEqualiser() {
try {
vizualizerHandler = VisualizerDbmHandler.Factory.newVisualizerHandler(getApplicationContext(), mediaPlayer);
audioVisualization.linkTo(vizualizerHandler);
} catch (Exception e) {
// TODO change it to snackbar message
Toast.makeText(mService, "Please Give Mic Permission", Toast.LENGTH_SHORT).show();
}
}
public void updateAlbumArt() {
Glide
.with(getApplicationContext())
.load(songThumb.get(musicPosition))
.placeholder(R.drawable.ic_default_icon)
.into(panelAlbumart);
Glide
.with(getApplicationContext())
.load(songThumb.get(musicPosition))
.placeholder(R.drawable.ic_default_icon)
.into(albumArt);
}
}
and this is my MusicService.class
public class MusicService extends MediaBrowserServiceCompat implements
MediaPlayer.OnCompletionListener,
AudioManager.OnAudioFocusChangeListener {
private static final String LOGTAG = "Friday";
public static int musicPosition;
public static MediaPlayer mediaPlayer;
Uri u;
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
Notification status;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && intent.getExtras() != null && intent.getExtras().containsKey("pos")) {
musicPosition = intent.getIntExtra("pos", 0);
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
}
if (arrayList != null) {
u = Uri.parse(songPath.get(musicPosition));
mediaPlayer = MediaPlayer.create(getApplicationContext(), u);
}
try {
playSong();
} catch (Exception e) {
next();
}
}
if (intent.getAction() != null) {
if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
previous();
} else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
play();
sendAction(1);
} else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
next();
}
}
return super.onStartCommand(intent, flags, startId);
}
private void playSong() {
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
showNotification();
}
private void sendAction(int action){
/* 1 for play or pause
* 2 for next
* 3 for previous
*/
Intent intent = new Intent();
intent.setAction(MainContainer.NOTIFICATION_ACTION);
intent.putExtra("action",action);
sendBroadcast(intent);
}
public int getPosition() {
return musicPosition;
}
public int getCurrentDuration() {
return mediaPlayer.getCurrentPosition();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public void changeSeekTo(int progress) {
mediaPlayer.seekTo(progress);
}
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
public MusicService getService() {
// Return this instance of LocalService so clients can call public methods
return MusicService.this;
}
}
public void next() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
musicPosition = (musicPosition + 1) % songPath.size();
u = Uri.parse(songPath.get(musicPosition));
mediaPlayer = MediaPlayer.create(getApplicationContext(), u);
playSong();
sendAction(2);
}
}
public void previous() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
musicPosition = (musicPosition - 1 < 0) ? songPath.size() - 1 : musicPosition - 1;
u = Uri.parse(songPath.get(musicPosition));
mediaPlayer = MediaPlayer.create(getApplicationContext(), u);
playSong();
sendAction(3);
}
}
public void play() {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
showNotification();
} else {
mediaPlayer.start();
showNotification();
}
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public void onAudioFocusChange(int i) {
mediaPlayer.stop();
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
sendAction(4);
next();
}
#Nullable
#Override
public BrowserRoot onGetRoot(#NonNull String clientPackageName, int clientUid, #Nullable Bundle rootHints) {
return null;
}
#Override
public void onLoadChildren(#NonNull String parentId, #NonNull Result<List<MediaBrowserCompat.MediaItem>> result) {
}
.
.
.
}
I don't know what happened.
Can anybody know about it.
There is already mediaPlayer.setOnCompleteListener inside VisualizerDbmHandler. So, for use it in other places you should use setInnerOnCompletionListener method to add own complete listener to VisualizerDbmHandler
Try do not recreate mediaPlayer but setup new source to it
**My conclusion is**: As you can see in source code of MediaPlayer - it will call onCompletion in cases that unhandled error appears). So, I think, because of recreating mediaPlayer in time, when you call startEqualizer ( recreate visualizerHandler and link it to visualizer view) inside the method linkTo - library call release to previous visualizerHandler and setup variable audioVisualizer to null, that provide you to calling stopRendering on null reference in case of onCompletion calling during to some error during reset/stop/release of MediaPlayer.
I have an activity that has a fragment with 18 pages. In some of the pages, there is a sound that can be played when the play button is clicked. However, when the user clicks on the play button and switches to another page, the sound from the previous page is still playing. How can make it play only in the relevant page, and stop if the page is switched?
public class PageFragment_Bon extends Fragment implements View.OnClickListener{
public static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
private Button start, stop, replay;
private MediaPlayer mediaPlayer;
int [] filer = new int[18];
public static PageFragment_Bon newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment_Bon fragment = new PageFragment_Bon();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_boenner, container, false);
start = (Button) view.findViewById(R.id.start);
start.setOnClickListener(this);
stop = (Button) view.findViewById(R.id.stop);
stop.setOnClickListener(this);
replay = (Button) view.findViewById(R.id.replay);
replay.setOnClickListener(this);
filer[2] = R.raw.Hello;
filer[4] = R.raw.Welcome;
filer[14] = R.raw.Intro;
filer[15] = R.raw.Farewell;
filer[16] = R.raw.Leave;
if(filer[mPage] != 0){
start.setVisibility(View.VISIBLE);
stop.setVisibility(View.VISIBLE);
replay.setVisibility(View.VISIBLE);
}
return view;
}
#Override
public void onResume() {
super.onResume();
if(mediaPlayer != null)
{
mediaPlayer.seekTo(0);
mediaPlayer.start();
}
}
#Override
public void onPause() {
super.onPause();
if(mediaPlayer != null)
{
mediaPlayer.pause();
}
}
#Override
public void onClick(View v) {
if(mediaPlayer == null)
mediaPlayer = MediaPlayer.create(getActivity().getBaseContext(), filer[mPage]);
if(v == start){
mediaPlayer.start();
}
else if(v == stop){
mediaPlayer.pause();
}
else if(v == replay){
mediaPlayer.seekTo(0);
mediaPlayer.start();
}
}
}
You can try something like this inside your fragments that have sounds
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(!isVisibleToUser){
if(mediaPlayer!=null) {
if (mediaPlayer.isPlaying()) {
try {
mediaPlayer.reset();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
By overriding setUserVisibleHint in your Fragment, you can determine when Fragment becomes visible
Edit
Start media player with try and catch (in case if there is any exception while you are trying to start media player)
if(v == start){
try {
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
It is better to override onPause() and onResume() in fragment. And we need to save the current position for media player. So, I am using the shared preference to save the position for media player.
In onCreateView,
mediaPlayer_position = getActivity().getSharedPreferences("PLAY_PAUSE", Activity.MODE_PRIVATE).getInt("CHECK_PLAY_PAUSE", 0);
#Override
public void onResume() {
super.onResume();
int position = getActivity().getSharedPreferences("PLAY_PAUSE", Activity.MODE_PRIVATE).getInt("CHECK_PLAY_PAUSE", 0);
if(position > 0) {
try {
mediaPlayer.setDataSource(mp3_link);//mp3_link from url to MediaPlayer data source
mediaPlayer.prepare();
} catch (Exception e) {
e.printStackTrace();
}
mediaPlayer.seekTo(position);
mediaPlayer.start();
}
}
#Override
public void onPause() {
super.onPause();
if(mediaPlayer.isPlaying()) {
mediaPlayer_position = mediaPlayer.getCurrentPosition();
getActivity().getSharedPreferences("PLAY_PAUSE", Context.MODE_PRIVATE).edit().putInt("CHECK_PLAY_PAUSE", mediaPlayer_position).apply();
mediaPlayer.pause();
}
}
Ref: "https://www.hrupin.com/2011/02/example-of-streaming-mp3-mediafile-with-android-mediaplayer-class"
I am in the process of building an android app for a local community radio station and I am getting this error in the LogCat:
2862-2862/pmelia.bcrfm V/MediaPlayer﹕ callback application
2862-2862/pmelia.bcrfm V/MediaPlayer﹕ back from callback
2862-2862/pmelia.bcrfm V/MediaPlayer﹕ isPlaying: 0
2862-2862/pmelia.bcrfm E/MediaPlayer﹕ Error (-38,0)
Here is my activity code
public class MainActivity extends ActionBarActivity implements View.OnClickListener, View.OnTouchListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnBufferingUpdateListener {
private Toolbar toolbar;
private Button btnPlay;
private Button btnPause;
private Button btnStop;
private SeekBar seekBar;
private MediaPlayer mediaPlayer;
private int lengthOfAudio;
//official broadcasting URL
private final String URL = "http://37.187.193.36:8002/listen.pls";
private final Handler handler = new Handler();
private final Runnable r = new Runnable() {
#Override
public void run() {
updateSeekProgress();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_appbar);
init();
}
private void init() {
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer,(DrawerLayout)findViewById(R.id.drawer_layout), toolbar);
btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(this);
btnPause = (Button) findViewById(R.id.btnPause);
btnPause.setOnClickListener(this);
btnPause.setEnabled(false);
btnStop = (Button) findViewById(R.id.btnStop);
btnStop.setOnClickListener(this);
btnStop.setEnabled(false);
seekBar = (SeekBar)findViewById(R.id.seekBar);
seekBar.setOnTouchListener(this);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Toast.makeText(this, "Hey you just hit " + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
btnPlay.setEnabled(true);
btnPause.setEnabled(false);
btnStop.setEnabled(false);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mediaPlayer.isPlaying()) {
SeekBar tmpSeekBar = (SeekBar)v;
mediaPlayer.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress() );
}
return false;
}
#Override
public void onClick(View view) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
}
catch (Exception e) {
Log.e("Error", e.getMessage());
}
switch (view.getId()) {
case R.id.btnPlay:
playAudio();
break;
case R.id.btnPause:
pauseAudio();
break;
case R.id.btnStop:
stopAudio();
break;
default:
break;
}
updateSeekProgress();
}
private void updateSeekProgress() {
if (mediaPlayer.isPlaying()) {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100));
handler.postDelayed(r, 1000);
}
}
private void stopAudio() {
mediaPlayer.stop();
btnPlay.setEnabled(true);
btnPause.setEnabled(false);
btnStop.setEnabled(false);
seekBar.setProgress(0);
}
private void pauseAudio() {
mediaPlayer.pause();
btnPlay.setEnabled(true);
btnPause.setEnabled(false);
}
private void playAudio() {
mediaPlayer.start();
btnPlay.setEnabled(false);
btnPause.setEnabled(true);
btnStop.setEnabled(true);
}
}
Any help would be appreciated, this is my first time doing this type of development.
I had the same problem... It has to be just the IP address with port number.
For this:
private final String URL = "http://37.187.193.36:8002/listen.pls";
Replace with:
private final String URL = "http://37.187.193.36:8002/";
So I got it to work finally in the end....First of all, thanks to #TennyTech.com for the little hint.
So to help ye people out, I will have an ans up on my github repo by tonight hopefully :) But do keep an eye out.
Hope this helps,
PatrickMelia
I am trying to make the background flash when music plays in my app but it isn't working as expected.
The music plays when a button is pressed. The background should be yellow when the music is off but flash quickly between yellow and purple when the music is playing.
At the moment it is yellow when off, changes to some dull grey when the music is playing and does not return to yellow when the music is off.
public class InstaRave extends Activity {
private static final String TAG = "InstaRave";
private static int isPlaying = 0; // 0 is not playing 1 is playing
private MediaPlayer mp;
public static int mPurple = color.mPurple;
public static int mYellow = color.mYellow;
public static int currentBackground = mYellow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insta_rave);
final Button play_button = (Button)this.findViewById(R.id.raveButton);
final RelativeLayout mRelativeLayout = (RelativeLayout) this.findViewById(R.id.topLevelLayout);
mp = MediaPlayer.create(this, R.raw.rave_mk);
Log.v(TAG, "Initializing sounds...");
play_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (isPlaying){
case 0:
changeBackground(mRelativeLayout);
startMusic();
isPlaying = 1;
rave();
break;
case 1:
changeBackground(mRelativeLayout);
stopMusic();
isPlaying = 0;
rave();
break;
default:
Log.e(TAG, "Ooops something went wrong");
}
}
private void stopMusic(){
Log.v(TAG, "Stopping sound...");
mp.stop();
//isPlaying = 0;
mp.prepareAsync();
}
private void startMusic(){
Log.v(TAG, "Playing sound...");
mp.start();
//isPlaying = 1;
}
private void rave(){
Log.v(TAG, String.valueOf(isPlaying));
if (isPlaying == 1){
Log.v(TAG, "Raving....");
new Rave().execute();
} else {
Log.v(TAG, "End the rave the po po is here...");
}
}
});
}
protected void onPause(){
super.onPause();
mp.release();
mp = null;
}
private void changeBackground(RelativeLayout mRelativeLayout){
if (currentBackground == mYellow){
currentBackground = mPurple;
mRelativeLayout.setBackgroundColor(currentBackground);
Log.v(TAG, "Background is: " + String.valueOf(currentBackground));
}
currentBackground = mYellow;
mRelativeLayout.setBackgroundColor(currentBackground);
Log.v(TAG, "Background is: " + String.valueOf(currentBackground));
}
private class Rave extends AsyncTask<Void, Void, Void> {
final RelativeLayout mRelativeLayout = (RelativeLayout) findViewById(R.id.topLevelLayout);
#Override
protected Void doInBackground(Void... params) {
while (isPlaying ==1){
try {
Thread.sleep(75);
publishProgress();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
protected void onProgressUpdate(Void... progress){
changeBackground(mRelativeLayout);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.insta_rave, menu);
return true;
}
}
Change your changeBackground() method to this:
private void changeBackground(RelativeLayout mRelativeLayout){
if (currentBackground == mYellow){
currentBackground = mPurple;
mRelativeLayout.setBackgroundColor(currentBackground);
Log.v(TAG, "Background is: " + String.valueOf(currentBackground));
}
else
{
currentBackground = mYellow;
mRelativeLayout.setBackgroundColor(currentBackground);
Log.v(TAG, "Background is: " + String.valueOf(currentBackground));
}
}