How to play background sound through out application? - android

How can I play Background Sound throughout my application, even if activities keeps on changing.
I have found code for playing sound in background for one activity as:
public class BackgroundSound extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
MediaPlayer player = MediaPlayer.create(YourActivity.this, R.raw.test_cbr);
player.setLooping(true); // Set looping
player.setVolume(100,100);
player.start();
return null;
}
}
I am not getting anyway to play sound in application content not activity context.
So I think there must be some way to achieve this using singleton class or service?
Play Background Sound in android applications
How to play audio in android
I have followed above both links but it doesn't seems to help me though, its playing sound but not with my instruction from second time, first it works where ever I want to start.
Any Help would be highly appreciated!!!

Related

Service or Activity for playing music in MediaPlayer App

I would like to develop a media player for Android on my own but I have a conception issue : should I use a Service or an Activity just for the player?
I have Fragments in my App and I would like to play a song when I click on one of the items within my music lists but I don't really know which of those 2 technologies I should use to allow music to keep playing even during navigation or outside the app.
Does it better to start a new Activity when a song is played and then keep the Activity running or launch a Service waiting for some events?
Thanks in advance.
The best solution for your app may be
i) Visualize your app with frontend ( like selecting music to play, pause, forward and other features )
ii) start service that runs in background which continues the activity process in background even if the activity is closed ..
You can accomplish this by implementing following ->
public class MyService extends Service implements MediaPlayer.OnPreparedListener {
private static final String ACTION_PLAY = "com.example.action.PLAY";
MediaPlayer mMediaPlayer = null;
public int onStartCommand(Intent intent, int flags, int startId) {
...
if (intent.getAction().equals(ACTION_PLAY)) {
mMediaPlayer = ... // initialize it here
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepareAsync(); // prepare async to not block main thread
}
}
/** Called when MediaPlayer is ready */
public void onPrepared(MediaPlayer player) {
player.start();
}
}
I think this is somehow helpful to you ..
If you want music playing in background, you should definitely use Service. Use activity only for UI-related operations. Since playing music is not UI-related operation, it should be done in Service. Please take a look here: http://developer.android.com/guide/topics/media/mediaplayer.html

Running two independent events simultaneously in android

I am new to android and stuck up at some point in the app i am currently developing. In my onCreate method I have two independent tasks : First is playing sounds in an array using for loop and Second is an onClickListener to an image that makes it animate on click. The sound starts perfectly as soon as I start the app, My problem is when I click the image, it animates as required but it stops the sound. How can I play sound and animation independent of each other? Any help/idea would be appreciated.
Use AsyncTask in android it will update the ui too in method updateProgress in android
You can use service for playing music.Services are designed to continually running in the background.
public class MyService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
MediaPlayer player = MediaPlayer.create(this, R.raw.audio);
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setVolume(1f, 1f);
player.start();

MediaPlayer Service Android

I am new to Android. I am creating service for Media Player so that it can continue to play song even if i close the application. I have created activity for Media Player and it is having all the functionality like play , pause , next , previous , seekbar and also includes oncompletionlistener . All works excellent. But Now i want that all should be managed by service.
I have Created MyService Class :
public class MyService extends Service {
public static MediaPlayer mp;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
mp = new MediaPlayer();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
But in my player activity i have created ArrayList for Songlist from which i am taking currentsongIndex and through it i am maintaining all the functionality like next , previous and all.. Now in service how do i get songlist which is also required in my activity ?? Where should i create MediaPlayer object mean in service or activity ??
for MediaPlayer I have reffered http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/ . For my media player code you can refer this site. Thanks.
Pleaze clear my doubt. I am so confused. Reply me soon..
You are on the right track. I have adapted from the SDK Samples; this is how I do it and it works great.
From your ArrayList (in your activity NOT from the Service) call
onListItemClick
and start an intent that starts the music service:
startService(new Intent(MusicService.ACTION_PLAY));
In your manifest you will need to add:
<intent-filter>
<action android:name="com.blah.blah.action.PLAY" />
<xxx xxx>
</intent-filter>
And of course in your Music Service you need to receive the Intent:
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent.getAction();
if (action.equals(ACTION_PLAY))
processPlayRequest();
}
Be sure to add Intents for skip, rewind, stop etc.
Let me know if this helps.
Getting the app to run in background should be taken care of by the 'Service' itself.
Try following this example http://www.vogella.com/articles/AndroidServices/article.html
A service is designed to work in the background.
I went through exactly the same thing! It's a long haul to develop even a really great mp3 player app. The answer is long.
Here are a few resources that really helped me. Android has a article on this very thing in their developer docs:
http://developer.android.com/guide/components/services.html
Pay attention to what it says at the bottom of this long article about bound services and running in the foreground.
Additionally, managing player state is what caused me the most headaches.
You'll also want to take a look at threading because spawning that new service will still execute everything on the Main UI Thread, sounds crazy but true. Take a look at the ExecutorService for managing thread pools. I wish I could tell you it was easier.
Unfortunately most of my formal training from all over the web but with android services comes from a paid site:
http://www.pluralsight.com/training/Courses/TableOfContents/android-services
It is a good resource for all programmers I think but has great sections about many aspects of android programming that are only covered briefly at other tutorial sites.
The resources at Vogella are good also, mentioned above.

How to get Android MediaPlayer() to stop when app is closed?

My android app creates a MediaPlayer() and plays a looping song. I need to have it stop playing when the user leaves the app. I also need to get at the volume buttons somehow, to let users adjust the songs volume... Any Ideas?
MediaPlayer mp;
public void setupMediaPlayer()
{
mp = MediaPlayer.create(context, R.raw.song);
mp.setLooping(true);
mp.start();
}
public void stopMediaPlayer()
{
mp.stop();
}
Per the first half of your question: you should get what you want if you call stopMediaPlayer() inside onPause() and onDestroy(). Example:
#Override
protected void onPause() {
super.onPause();
stopMediaPlayer();
}
Per the second half: Try taking a look at the AudioManager class (particularly AUDIO_FOCUS_GAIN), and see if that can handle what you're looking for.
Make sure the looping audio makes sense in the context of the app, though...if there's one thing I don't miss from the amateur websites of the mid-90's it's that awful MIDI background music that everyone seemed to put in them...
Also think about onResume(), to continue your looping song when the user comes back to your app.
stopMediaPlayer didn't work for me as per eldarerathis' answer but this did:
#Override
protected void onPause() {
super.onPause();
releaseMediaPlayer();
}
Dunno why though...
Edited:
According to the course I'm doing though this is the correct way to do it.
Maybe one day I'll figure out the difference. :)

How to check something at regular intervals?

Beginner here, I have a simple question.
In Android what would be the best what to check for something at regular intervals?
Please bear with me, I'll try to explain the best I can --
For example my audio app is very simple, a main activity and a service. The main activity has a UI with two buttons, start and stop audio. I press start and the audio service starts. Likewise when I click Stop the service stops and the audio ends. If isLooping() is hard-coded to true there is no issue because the audio never ends unless I hit stop button, which stops the audio service and also resets the button states.
This is an issue now because I set isLooping() to false so the audio doesn't loop. So the audio will stop playing but the service is still running.
I want to be able to detect when the audio stops so I can set the states of the UI buttons. So I need something that is always checking whether audio is playing (i.e. check player.isPlaying() so I can end the service and set the enable/disable state of the buttons.
I figured out binding to the service so I can access the MediaPlayer controls via my main activity so I know the code to check if it's playing, but WHERE do I put this code so it's checked all the time?
Am I making sense? I know this is probably very simple. Thanks for any help.
You can repeat it with the TimerTask and Timer. Code below:
public final void RepeatSoundFunction(){
t = new Timer();
tt = new TimerTask() {
#Override
public void run() {
mp.seekTo(0); //Reset sound to beginning position
mp.start(); //Start the sound
t.purge(); //Purge the sound
}
};
t.schedule(tt, 10*1000); //Schedule to run tt (TimerTask) again after 10 seconds
}
then you set a MediaPlayer onCompletionListener and in there you put this.
Inside the run-code you can check for other things than
music, I just show an example with the audio.

Categories

Resources