Playing Background sound in Android - android

I am trying to play a background sound which runs throughout the application. Here I have 3 activities and the sound is started when the MAIN activity launches.
I want to achieve these:
1) play the bg sound continuously throughout the app whatever activity loads.
2) Switch off the sound when user clicks sound off button.
3) Stop the sound when the app closes.
So far I have tried this code to start the sound but it keeps on playing even if the app is closed.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audioPlayer();
}
boolean isPlayingSound = true;
public void onClickSound(View view) {
final Button btn1 = (Button) findViewById(R.id.button3);
if(isPlayingSound){
btn1.setBackgroundResource(R.drawable.sound00);
isPlayingSound=false;
audioPlayer(false);/*Sound doesn't stops here*/
}
else{
btn1.setBackgroundResource(R.drawable.sound11);
isPlayingSound=true;
audioPlayer(true);
}
}
public void audioPlayer(boolean status){
MediaPlayer mp = MediaPlayer.create(this, R.raw.bg);
if(status) {
mp.start();
}
else {
mp.stop();
}
}
Can anyone plz have a look and help me out here. Thanks for help!!

you can playback the audio move to Service. you can reference ASOP music code
or look
Binding to a Started Service
As discussed in the Services document, you can create a service that is both started and bound. That is, the service can be started by calling startService(), which allows the service to run indefinitely, and also allow a client to bind to the service by calling bindService().
If you do allow your service to be started and bound, then when the service has been started, the system does not destroy the service when all clients unbind. Instead, you must explicitly stop the service, by calling stopSelf() or stopService().

Related

Android MediaController Play/Pause button and Seekbar doesn't Refresh

I am using MediaController.MediaPlayerControl in order to display a MediaController at the bottom of my Custom View but I can't get it to work properly. When I play music for first time then there should be pause button visible but instead there is play and when I press that button then the music is paused correctly and state remains the same and after that its working properly. Also when I play next song, the old MediaController widget gets overlapped with the new one. And sometimes the progress/seek bar doesn't refresh while the music is playing. It just updates itself when something on the MediaController is pressed (Play/Pause, forward, etc).
I found these questions similar to mine but I don't think the answers they got will solve my problem.
Android mediacontroller Play Pause controls not refresh properly
Android MediaController seekbar not refreshing
Android VideoView Playback Controls Show "Play" Initially Instead of "Pause" Even Though File is Already Playing
This is how I initialize the controller:
private void setController()
{
controller = new MusicController(this);
controller.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
playNext();
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
playPrev();
}
});
controller.setMediaPlayer(this);
controller.setAnchorView(findViewById(R.id.song_list));
controller.setEnabled(true);
}
This is how I show controller:
public void playMusic()
{
musicSrv.playSong(); //Play song in a service
setController();
controller.show(0);
controller.requestFocus();
}
I had exactly this problem. Don't know if you still need help, but I thought I'd post anyway. For posterity, are you following this tutorial?
First, the easy problem: you're getting multiple instances of your controls because of repeated calls to setController(). Change the first line of your function to:
if (controller == null) controller = new MusicController(this);
With regards to the play button malfunctioning, I believe it's because you're showing it before the music player has been prepared (disclaimer: I'm a newbie to Android myself, and the following are the things I've found to have worked).
Set up a broadcast from your music-playing service to notify your music-controlling activity when the musicplayer has been prepared. Append the following function in your music-playing service to broadcast intent:
#Override
public void onPrepared(MusicPlayer player) {
// Do some other stuff...
// Broadcast intent to activity to let it know the media player has been prepared
Intent onPreparedIntent = new Intent("MEDIA_PLAYER_PREPARED");
LocalBroadcastManager.getInstance(this).sendBroadcast(onPreparedIntent);
}
Set up a broadcast receiver in your music-controlling activity to receive the intent broadcast by your service. Add the following class to your activity:
// Broadcast receiver to determine when music player has been prepared
private BroadcastReceiver onPrepareReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent i) {
// When music player has been prepared, show controller
controller.show(0);
}
};
Register your receiver in your activity's onResume() method:
// Set up receiver for media player onPrepared broadcast
LocalBroadcastManager.getInstance(this).registerReceiver(onPrepareReceiver,
new IntentFilter("MEDIA_PLAYER_PREPARED"));
Depending on the structure of your code, you'll have to do some general tidying up. In my code, I've only called setController() twice: from the onCreate() and onResume() methods in my activity. I also only call controller.show(0) from my broadcast receiver, and my onResume() method.

Android Media Player doesn't play after app has been left for a while in the background

Bit of a strange one this and I can't work out what's happening.
When I launch my app (a game) the music starts playing. I have a button which turns the music on and off. The settings are saved to shared prefs so they are retained.
All works well, you can press the home key, re-invoke the app, leave it in the background while doing other things etc. However, if the app is left in the background for a while (say, overnight), and then re-invoked. Everything works apart from the music.
You can go into the main menu, hit the 'music on/off' button multiple times, but get nothing.
The only way to start the music is to kill the app (or exit correctly, ie, press the 'back' key from the main menu) and then relaunch it so everything is re-created from scratch.
I've confirmed that the 'music' object is still valid and the 'music on/off' button presses are being registered.
Has anyone has similar issues with Media Player? I can't work out what I am (or am not doing) to cause this.
Code
This is my media player class:
public class MusicMan implements MediaPlayer.OnPreparedListener {
MediaPlayer musicPlayer;
MusicMan(Context myContext){
musicPlayer = MediaPlayer.create(myContext, R.raw.music);
musicPlayer.setVolume(.6f, .6f);
}
public void listener(){};
public void start(){
musicPlayer.setLooping(true);
musicPlayer.start();
}
public void stop(){
musicPlayer.stop();
}
public void pause(){
musicPlayer.pause();
}
public int getPos(){
return musicPlayer.getCurrentPosition();
}
public void skipTo(int position){
musicPlayer.seekTo(position);
}
#Override
public void onPrepared(MediaPlayer arg0) {
}
}
And then I simply crate an object like so:
MusicMan music = new MusicMan(view.getContext());
And then I just start and stop the music using the methods in the MusicMan class:
music.start();
You need to use
musicPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
Use this where you set new MediaPlayer player. It sets the wake lock to MediaPlayer and don't let CPU go sleep till you yourself didn't kill or stop application.

Play/Stop sound from another activity

I have 3 activities. I want to play one background music to all this activity. I made this possible by. Doing this.
In activity 1:
bgmp = MediaPlayer.create(this, R.raw.menu);
bgmp.setLooping(true);
bgmp.start();
This will make my music play up to the 3rd acitivity. At activity three. I need to stop this background music because another background music will be played when I go to the 4th activity. How can I stop the music at the 3rd acitivity that was created at the 1st activity. Any ideas? Thanks!
Define Method in common class with require parameters and use that Method in your activities.
public class CommonMethod {
public static MediaPlayer player;
public static void SoundPlayer(Context ctx,int raw_id){
player = MediaPlayer.create(ctx, raw_id);
player.setLooping(false); // Set looping
player.setVolume(100, 100);
//player.release();
player.start();
}
}
Within in your third activity, code for stop media.
CommonMethod.player.stop();
Create a service to play sound and move all your player code to service.
After that bind your activity to this service and control the music player for (play next, back, pause, stop etc.) features.
Make a singleton class and add you music playing code into it for stopping and starting and use that singleton class in all your 3 activities for eg:
public class MusicManager {
private static MusicManager refrence = null;
public static MusicManager getInstance(){
if(refrence == null){
refrence = new MusicManager ();
}
return refrence;
}
}
add a public method to this singleton class to start and stop music like
public void initalizeMediaPlayer(Context context, int musicId){
// add initalization of media player in it and loop it
}
public void startPlaying(){
// add code to start playing music
}
public void stopPlaying(){
// add code to stop playing music
}
And for making use this class use like this
MusicManager.getInstance().initalizeMediaPlayer(this, R.raw.menu); // to initalize of media player
MusicManager.getInstance().startPlaying();// to start playing music
MusicManager.getInstance().stopPlaying(); // to stop playing music
Let me know if this helps you.
Mean while you can also use service to perform this task as service runs in background . you can start service and stop service any time in your code
You Should Start Service which runs in background and write code for playing music in the service..
All you have to do is add this piece of code to your intent to the last activity:
yourMediaPlayer.pause()
So the whole code would be :
yourMediaPlayer.pause();
Intent i ...
startActivity(i);
Just put player.stop() function inside button which takes you to next activity:
example: #Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
player.stop();
Intent i=new Intent(iotmain.this,MainActivity.class);
startActivity(i);
Toast.makeText(getBaseContext(),"Chatting mode ON",Toast.LENGTH_SHORT).show();
}

Muting streams in Android

I've built a small app that mutes/unmute the music stream using the class AudioManager.
In fact, it works until I close the application. i.e. I've muted the sream, I close the app, I restart the app and the button doesn't unmute the stream any more. I've searched in the net but no one seems to have met this problem.
Here's my code:
public class ControlloVolume extends Activity {
ToggleButton tb_mute;
Button btn_mute;
AudioManager mAudioManager;
boolean mute;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_controllo_volume);
tb_mute = (ToggleButton) findViewById(R.id.tb_mute);
btn_mute = (Button) findViewById(R.id.btn_mute);
mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
if(mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC)==0){
mute = true;
tb_mute.setChecked(mute);
}else{
mute = false;
tb_mute.setChecked(mute);
}
}
public void onButtonClicked(View view){
if(!mute){
mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
tb_mute.setChecked(true);
mute = true;
}else{
mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
tb_mute.setChecked(false);
mute = false;
}
}
First, beware it's not recommended
For a better user experience, applications MUST unmute a muted stream
in onPause() and mute it again in onResume() if appropriate.
But I assume you know what you're doing, so here we go.
Note this line from the docs on setStreamMute
The mute command is protected against client process death: if a
process with an active mute request on a stream dies, this stream will
be unmuted automatically.
I've checked on my device and indeed, when I just exit my activity, stream stays muted. But as soon as I kill the process, mute goes away.
Take a look at activity lifecycle.
As your current approach will not work reliably, you could write a foreground service which will trigger the mute - start that service from your activity.
Also you would likely need to setStreamSolo.
Two important things.
Volume==0 and muted are NOT the same thing. I.e. stream can have volume==0 but be not muted. Though if stream is muted, volume will always be 0
mute requests are cumulative. I.e. if you've set mute twice, you must unmute twice as well - your code doesn't handle that
As a side note, for such app you would probably want to use widget instead of activity.
Off topic. It seems surprisingly lot of people don't quite get how booleans work.
And as I see code such as yours regulary, here is a bit streamlined rewrite.
#Override
public void onCreate(Bundle savedInstanceState) {
// ... setup just like you did
// boolean is just like any other type. You can assign not only
// constants, but expressions too
mute = (mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC)==0);
tb_mute.setChecked(mute);
}
public void onButtonClicked(View view){
mute = !mute; // invert value
mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, mute);
tb_mute.setChecked(mute);
}

Android event listeners for audio

I'm playing around with Android to learn the API and I'm trying to code an activity which can listen for changes in audio events. For example, the activity I created plays a random ringtone when you press a button. The button displays a text saying "Random Ringtone", but when you press the button it says "Stop" and pressing it will, of course, stop playing the ringtone.
However, the problem is that when the ringtone stops playing on its own, the button still says "stop".
I've looked around to try to find an event listener that could listen for when the ringtone stops playing, but I can't seem to find one. I've seen some info out there about creating your own listeners, but I'm not interested in doing that (a little advanced for me right now).
Does an event listener of this type exist?
I may be wrong but I think the only audio class which raises an event when it finishes playing is the MediaPlayer class. Something like this should work...
public class MyActivity extends Activity
implements MediaPlayer.OnCompletionListener {
MediaPlayer player = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
player = new MediaPlayer();
player.setOnCompletionListener(this);
...
}
#Override
public void onCompletion(MediaPlayer mp) {
// Called when playback is complete
...
}
}

Categories

Resources