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));
}
}
Related
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 created android application to stream online radio stations but when I click start button to play radio it won't start.In service I read ip address of file from url and add it to string.When user selects radio station I add port to string with ip address.Problem starts in mediaPlayer.setOnPreparedListener !!!
public class BackgroundService extends Service implements OnCompletionListener
{
MediaPlayer mediaPlayer;
private String STREAM_URL;
final String textSource = "http://audiophileradio.stream/Ip.txt";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
new MyTask().execute();
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
#Override
public boolean onUnbind(Intent intent)
{
return super.onUnbind(intent);
}
private class MyTask extends AsyncTask<Void, Void, String>
{
String textResult;
#Override
protected String doInBackground(Void... params) {
URL textUrl;
try {
textUrl = new URL(textSource);
BufferedReader bufferReader
= new BufferedReader(new InputStreamReader(textUrl.openStream()));
String StringBuffer;
String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textResult = stringText;
return textResult;
} catch (MalformedURLException e) {
e.printStackTrace();
textResult = e.toString();
} catch (IOException e) {
e.printStackTrace();
textResult = e.toString();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.d("DebugTag", "Value: " + textResult);
super.onPostExecute(result);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(BackgroundService.this);
String radio = sharedPreferences.getString("station", "8000");
if (radio != null)
{
STREAM_URL += ":" + radio;
}
mediaPlayer = new MediaPlayer();
if (!mediaPlayer.isPlaying())
{
try
{
mediaPlayer.reset();
mediaPlayer.setDataSource(STREAM_URL);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
mediaPlayer.start();
}
});
} catch (IOException e)
{
e.printStackTrace();
}
}
mediaPlayer.setOnCompletionListener(BackgroundService.this);
}
}
}
public class Main extends Fragment
{
private ImageButton buttonPlay;
private MediaPlayer mPlayer;
Intent playbackServiceIntent;
private SeekBar volumeSeekbar = null;
private AudioManager audioManager = null;
View view;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.fragment_main,container,false);
buttonPlay = (ImageButton) view.findViewById(R.id.buttonPlay);
mPlayer = new MediaPlayer();
initControls();
buttonPlay.setTag(1);
buttonPlay.setImageResource(R.drawable.play);
buttonPlay.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
if (Integer.parseInt(buttonPlay.getTag().toString()) == 1)
{
buttonPlay.setImageResource(R.drawable.stop);
view.setTag(0);
getActivity().startService(playbackServiceIntent);
Log.e("Play", "onStop");
Toast.makeText(getActivity(), "Play", Toast.LENGTH_SHORT).show();
} else
{
buttonPlay.setImageResource(R.drawable.play);
view.setTag(1);
mPlayer.stop();
getActivity().stopService(playbackServiceIntent);
Log.e("Stop", "onPlay");
Toast.makeText(getActivity(), "Stop", Toast.LENGTH_SHORT).show();
}
}
});
playbackServiceIntent = new Intent(getActivity(), BackgroundService.class);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Audiophileradio");
}
private void startService()
{
getActivity().startService(new Intent(getActivity(),BackgroundService.class));
}
private void stopService()
{
getActivity().stopService(new Intent(getActivity(),BackgroundService.class));
}
private void initControls()
{
try
{
volumeSeekbar = (SeekBar) view.findViewById(R.id.seekBar);
audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
volumeSeekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
//volumeSeekbar.setMax(100);
volumeSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar arg0)
{
}
#Override
public void onStartTrackingTouch(SeekBar arg0)
{
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2)
{
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
//volume.setText("Volume : " + progress + "%");
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
prepareAsynch should be called after setOnPreparedListener, otherwise it may happen that prepareAsynch finished working before the listener is assigned.
I have fixed the problem! Radio didn't work because I forgot to add http:// in ip address after reading it from url !!!
In my application I can successfully call a method flash_toggle_times(progress); when toggle Button is pressed. But when I am calling same method in public void onStopTrackingTouch(SeekBar seekBar) It is not being called. Do not know why?
Here is complete code
public class MainActivity extends ActionBarActivity implements OnSeekBarChangeListener {
SeekBar seekBar;
TextView textView;
ToggleButton toggleButton;
boolean positionON = false;
private Camera mCamera;
private Camera.Parameters mParams;
boolean lightON = false;
boolean changeIntensity = false;
int progress = 0;
private String TAG = "SeekBar LOG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeVariables();
textView.setText("Covered : " + seekBar.getProgress() + "/" + seekBar.getMax());
seekBar.setOnSeekBarChangeListener(this);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// positionON = (isChecked) ? true : false;
positionON = isChecked;
if (isChecked) {
//Here flash_toggle_times(progress) is being called successfully
// flash_toggle_times(progress);
} else {
}
}
});
}
private void initializeVariables() {
seekBar = (SeekBar) findViewById(R.id.m_seekbar);
textView = (TextView) findViewById(R.id.m_tv);
toggleButton = (ToggleButton) findViewById(R.id.m_toggle_button);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
textView.setText("Covered On Stop: " + progress + "/" + seekBar.getMax() + "\n" + changeIntensity);
// If button is On, Turn on Light
Toast.makeText(getApplicationContext(), "StopTrackingTouch: " + progress, Toast.LENGTH_SHORT).show();
if(progress > 0){
//Here when this method is not being called.
flash_toggle_times(progress);
Toast.makeText(getApplicationContext(), "Calling in if", Toast.LENGTH_SHORT).show();
}
Log.d(TAG, "StopTrackingTouch");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
Log.d(TAG , "StartTrackingTouch()");
}
#Override
public void onProgressChanged(SeekBar seekBar, int progressValue, boolean fromUser) {
progress = progressValue;
// Toast.makeText(getApplicationContext(), "ProgressChanged : " + progress, Toast.LENGTH_SHORT).show();
Log.d(TAG,"ProgressChanged");
}
public void flash_toggle_times(final int delay) {
mCamera = Camera.open();
final Parameters p = mCamera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
Thread t = new Thread() {
public void run() {
try {
// Switch on the cam for app's life
if (mCamera == null) {
// Turn on Cam
mCamera = Camera.open();
try {
mCamera.setPreviewDisplay(null);
} catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
}
final int[] counter = {delay};
while(positionON )
{
if(counter[0] > 0){
toggleFlashLight();
sleep(counter[0]*100);
}
}
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
} catch (Exception e){
e.printStackTrace();
}
}
};
t.start();
}
public void turnOn(){
if (mCamera != null) {
// Turn on LED
mParams = mCamera.getParameters();
mParams.setFlashMode(Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(mParams);
}
lightON = true;
}
public void turnOff(){
// Turn off flashlight
if (mCamera != null) {
mParams = mCamera.getParameters();
if (mParams.getFlashMode().equals(Parameters.FLASH_MODE_TORCH)) {
mParams.setFlashMode(Parameters.FLASH_MODE_OFF);
mCamera.setParameters(mParams);
}
}
lightON = false;
}
private void toggleFlashLight() {
if (!lightON) {
turnOn();
} else {
turnOff();
}
}
}
I am trying to play background music in simple game on Android using Services.
Using the link: Android Life Cycles
But this code doesn't work properly, onResumeActivity, onPauseActivity are called but the music keep running in background even when the onPauseActivity method is called.
The music keeps on playing while the app is in background.
is there any other way to play background music in an Android App/Game??
I think this code will work for you. Add this class (Enclosed in your activity class).
public class BackgroundMusic extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
MediaPlayer backgroundmusic = MediaPlayer.create(YourActivity.this, R.raw.yourbackgroundmusic);
player.setVolume(100,100);
player.setLooping(true);
player.start();
return null;
}
}
And create it
BackgroundMusic bm = new BackgroundMusic();
On onResume method:
public void onResume() {
super.onResume();
bm.execute(null);
}
And onPause method:
public void onPause() {
super.onPause();
bm.cancel(true);
}
Hope this help!
public class SoundGameBaseActivity extends Activity {
public static boolean isSoundPaused = false;
public static MediaPlayer mp;
protected static final String TAG = SoundGameBaseActivity.class.getName();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
playMusic();
}
public static boolean isAppWentToBg = false;
public static boolean isWindowFocused = false;
public static boolean isMenuOpened = false;
public static boolean isBackPressed = false;
#Override
protected void onStart() {
Log.d(TAG, "onStart isAppWentToBg " + isAppWentToBg);
applicationWillEnterForeground();
super.onStart();
}
private void applicationWillEnterForeground() {
if (isAppWentToBg) {
//Google Analytics
MyApp.getInstance().trackScreenView("ApplicationActivated");
isAppWentToBg = false;
// Toast.makeText(getApplicationContext(), "App is in foreground",
// Toast.LENGTH_SHORT).show();
playMusic();
}
}
#Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop ");
applicationdidenterbackground();
}
public void applicationdidenterbackground() {
if (!isWindowFocused) {
isAppWentToBg = true;
Toast.makeText(getApplicationContext(),
"App is Going to Background", Toast.LENGTH_SHORT).show();
stopMusic();
}
}
public void TurnOnMusicAgain() {
}
void playMusic() {
if (mp == null) {
mp = MediaPlayer.create(this, R.raw.background1);
// mp.prepare();
mp.start();
mp.setLooping(true);
} else {
if (mp.isPlaying()) {
} else {
Log.e("", "coming back");
mp.start();
}
}
}
void stopMusic() {
if (mp != null)
mp.pause();
}
#Override
public void onBackPressed() {
if (this instanceof StartScreen) {
} else {
isBackPressed = true;
}
Log.d(TAG,
"onBackPressed " + isBackPressed + ""
+ this.getLocalClassName());
super.onBackPressed();
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
isWindowFocused = hasFocus;
Log.e("Is Window Focus", "" + isWindowFocused);
if (isBackPressed && !hasFocus) {
isBackPressed = false;
isWindowFocused = true;
}
super.onWindowFocusChanged(hasFocus);
}
}
Please, I need my streaming audio player to be controlled from two different fragments:
Radiofragment and AboutFragment.
and here's my radio fragment
public class RadioFragment extends Fragment implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener{
AudioManager am;
ImageButton btnPlay = null;
private boolean isPlaying;
private PlayerManager playerManager;
private View view;
public RadioFragment(boolean p, PlayerManager pmanager){
this.isPlaying = p;
this.playerManager = pmanager;
}
#Override
public View onCreateView(LayoutInflater l, ViewGroup container, Bundle onSavedInstance){
super.onCreateView(l, container, onSavedInstance);
view = l.inflate(R.layout.activity_radio, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
btnPlay = (ImageButton)view.findViewById(R.id.btnPlay);
addButtonListeners();
}
private void addButtonListeners()
{
btnPlay.setAlpha(155);
btnPlay.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
onClickBtnPlay(v);
}
});
}
protected void onClickBtnPlay(View v)
{
if (isPlaying){
playerManager.pause();
isPlaying = false;
}
else{
if (playerManager == null){
playerManager = new PlayerManager(getString(R.string.link_streaming_radio), RadioFragment.this);
}
playerManager.play();
isPlaying = true;
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra)
{
StringBuilder sb = new StringBuilder();
sb.append("Media Player Error: ");
switch (what)
{
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
}
sb.append(" (" + what + ") ");
sb.append(extra);
Log.e(MainActivity.TAG, sb.toString());
return true;
}
#Override
public void onPrepared(MediaPlayer mp)
{
mp.start();
}
#Override
public void onCompletion(MediaPlayer mp)
{
mp.stop();
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent)
{
Log.d(MainActivity.TAG, "PlayerService onBufferingUpdate : " + percent + "%");
}
}
in my AboutFragment, I have a layout with a play/pause button and
protected void onClickBtnPlay(View v)
{
if (isPlaying){
playerManager.pause();
isPlaying = false;
}
else{
if (playerManager == null){
playerManager = new PlayerManager(getString(R.string.link_streaming_radio), AboutFragment.this);
}
playerManager.play();
isPlaying = true;
}
}
here is the class where I controll the player:
public class PlayerManager{
private String xmlUrl;
private String server;
private MediaPlayer mp;
public PlayerManager(Fragment owner)
{
this.owner = owner;
this.server = "";
}
public void play()
{
server = path_to_server;
playMusic();
}
public void pause()
{
mp.stop();
mp.reset();
}
private void playMusic()
{
Uri myUri = Uri.parse(this.server);
try
{
if (mp == null){
this.mp = new MediaPlayer();
}
else{
mp.stop();
mp.reset();
}
mp.setDataSource(owner.getActivity(), myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener((OnPreparedListener) this.owner);
mp.setOnBufferingUpdateListener((OnBufferingUpdateListener) this.owner);
mp.setOnErrorListener((OnErrorListener) this.owner);
mp.setVolume(100,100);
mp.prepareAsync();
Log.d(MainActivity.TAG, "Done");
}
catch (Throwable t)
{
Log.d(MainActivity.TAG, t.toString());
}
}
}
can it be done with this kind of implementation or I have to use another approach?
Because I tried to pass playerManager via constructor but it seems to be in other activity context
so i get class cast exceptions. I also tried to pass Radiofragment context and got some null pointer exceptions
both from this last catch block above.
I need some light here, please..
thank you in advance!
You should have a foreground Service, containing the PlayerManager. You will then send play/pause commands from any activity or fragment you want.