Playing BG Music Across Activities in Android
Hello! First time to ask a question here at stackoverflow. Exciting! Haha.
We're developing an Android game and we play some background music for our intro (we have an Intro Activity) but we want it to continue playing to the next Activity, and perhaps be able to stop or play the music again from anywhere within the application.
What we're doing at the moment is play the bgm using MediaPlayer at our Intro Activity. However, we stop the music as soon as the user leaves that Activity. Do we have to use something like Services for this? Or is MediaPlayer/SoundPool enough? If anyone knows the answer, we'd gladly appreciate your sharing it with us. Thanks!
Asked by: Catherine937 | Posted: 20-01-2022
Answer 1
You can also create a service which play music using mediaplayer as below.
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc); //OR stopService(svc);
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.idil);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TODO
}
public IBinder onUnBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onStop() {
}
public void onPause() {
}
@Override
public void onDestroy() {
player.stop();
player.release();
}
@Override
public void onLowMemory() {
}
}
Answered by: Alfred575 | Posted: 21-02-2022
Answer 2
Create a static SoundManager using either SoundPools or MediaPlayers.
Create a static flag called keepMusicGoing.
Start the music when the first activty is created.
When switching actvities set keepMusicGoing to true.
On the onStop event of your activities check if keepMusicGoing is true,if so leave the music on, then set keepMusicGoing to false.
If they press the home button the keepMusicGoing flag will be false so the music will stop when the activity loses focus.
Email me and I can send you a couple SoundManagers that I wrote one uses MediaPlayers and the other SoundPools
Chad
Answered by: Melissa925 | Posted: 21-02-2022Answer 3
If I understand your situation correctly, then I have confronted the same problem a few times. I am using a different thread to play music in my applications. This implementation passes a static reference to a Context that I know will be alive for the time that the music will be playing.
public class AudioPlayer extends Thread {
private Context c;
private Thread blinker;
private File file;
public AudioPlayer (Context c, File file) {
this.c = c;
this.file = file;
}
public void go () {
blinker = this;
if(!blinker.isAlive()) {
blinker.start();
}
}
public void end () {
Thread waiter = blinker;
blinker = null;
if (waiter != null)
waiter.interrupt ();
}
public void run () {
MediaPlayer ap = MediaPlayer.create(c, Uri.fromFile(file));
int duration = ap.getDuration();
long startTime = System.currentTimeMillis();
ap.start();
try {
Thread thisThread = Thread.currentThread();
while (this.blinker == thisThread && System.currentTimeMillis() - startTime < duration) {
Thread.sleep (500); // interval between checks (in ms)
}
ap.stop ();
ap.release ();
ap = null;
} catch (InterruptedException e) {
Log.d("AUDIO-PLAYER", "INTERRUPTED EXCEPTION");
ap.stop ();
ap.release();
ap = null;
}
}
}
Answered by: Alissa482 | Posted: 21-02-2022
Answer 4
First i used the method where to keep a "keepMusicPlaying" flag provided by Chad. I think its more elegant to just use the onStart and onStop methods of your activitys.
Create an own class "SoundManager" and call some onStart and onStop classes in it from all your activitys onStart and onStop (or use a base activity class). Keep track of the onStart and onStop with a startCounter(startCounter++ in onstart and startCounter-- in onstop). Because the start of a new activity is called before the onStop of the old activity you always know if the onStart is called for the first Time (startCounter == 1) or started from another of your activitys (startCounter == 2). Same with the onStope(startCounter == 0 means the App was closed, startCounter == 1 means its just the stop from an old activity but there is a new).
This way you encapsulate everything into your SoundManager instead of having to call some keepMusicPlaying method/flag on every activity start inside your app.
public void OnStart()
{
startCounter++;
if (startCounter == 1)
{
//start music here
}
public void OnStop()
{
startCounter--;
if (startCounter == 0)
{
// stop music here
}
}
Answered by: Ryan835 | Posted: 21-02-2022
Answer 5
You can try using the AsyncPlayer but you should keep a reference to the class in order to stop the sound from playing.
You can create a Uri to a local resource using Uri uri = Uri.parse("android.resource://com.stackoverlof.android/raw/
beep.mp3");
.
Hope this helps.
Answered by: Roland359 | Posted: 21-02-2022Answer 6
By combining Chad's and Kedu's answers and adding my own flavor, I created this working solution:
// Parent Activity which every Activity extends
public class ParentActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onStart() {
super.onStart();
Music.onStart();
}
@Override
protected void onStop() {
super.onStop();
Music.onStop();
}
}
// Controller class for handling background music
public abstract class Music {
private static MediaPlayer mediaPlayer;
private static int startCounter = 0;
public static void onStart() {
startCounter++;
if (startCounter == 1) {
mediaPlayer = MediaPlayer.create(InitializeActivity.getContext(), R.raw.background_music);
mediaPlayer.setLooping(true);
mediaPlayer.setVolume(1f, 1f);
mediaPlayer.start();
}
}
public static void onStop() {
startCounter--;
if (startCounter == 0) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
}
And that's it, super simple!
Answered by: Sawyer278 | Posted: 21-02-2022Similar questions
android - Switch between two activities and keep music playing
Here is what I want to achieve in my app: I have 3 menus in the startup page: PLAY , INSTRUCTIONS , HIGH SCORE.
I have theme music playing in the background with the help of MediaPlayer object. I just want that the theme music should be playing for the PLAY and INSTRUCTIONS menu, uninterrupted, i.e, if the activity changes from MAIN MENU to INSTRUCTIONS and vice-versa , the music should be playing uninterrupted. But the mu...
Android: playing a lot of short length audio tracks in different activities
I have 10 similar activities and in each i have 2 audio tracks.
I try creating 2 media player each time an activity is created and release it each time I move to another activity but the memory won't actually release and after some time the app crashes.
How can I play a lot of different audio tracks without having the app crashes on me?
here is the code of one of the activities:
public class First exten...
android - How can I let stream online keep playing when I switch between activities?
I've spent nearly the entire day trying to find a solution for a specific MediaPlayer problem, the code below is for my main activity I'm building an Android app that will stream radio station but when I switch between activity the stream stop,
How can I let stream online (radio) keep playing when I switch between activities ?
package radiofm.arabel;
import android.app.ProgressDialog;
impor...
How to stay connected to an Android service between multiple activities?
I have multiple activities and one service. In MainActivity I successfully connect to service (using a class that implements ServiceConnection + bindService() + startService()) but when I try to apply same method in other activity I see in LogCat a error:
01-15 22:29:37.438: ERROR/ActivityThread(12206): android.app.ServiceConnectionLeaked:
Activity...
Android: What is better - multiple activities or switching views manually?
I have developed some apps for Android, and this questions stays always:
How should I structure my UI? Should I launch activity after activity and leave the phone to make the "back" button, or should I choose more optimized, but more complex to implement, way with switching manually Views and then manually doing the "Back" button functionality?
What do you think (or know) is the better practice?
android - Is it better to create new Activities or just create a different Layout and replace the existing layout?
Since I am new to Android, I am now thinking on what is the correct way of doing things.
As it stands, the application I'm writing has 4 different screens:
Screen 1 - list of nodes (main screen)
Screen 2 - options menu, tableLayout with buttons
Screen 3 - navigation
Screen 4 - text details on version etc
These screens can be navigated to/from using a "header" ...
android - freeze on sending certain bitmaps to activities
Basically I receive the Image's URI from the Gallery, then created a Bitmap and want to send to another activity for displaying:
Uri imageUri = intent.getData();
mBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
Intent intent = new Intent(TakePictureActivity.this, PreviewActivity.class);
intent.putExtra(EXTRA_BITMAP_DATA, mBitmap);
startActivityForResult(intent, REQUEST_PREVIEW);
...
problem in passing data in android Activities?
can any one guide me what mistake am i doing in this code??? it not seems to be working..
i have two activies
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent(DataPassing.this, DataPassing2.class);
Bundle b = new Bundle();
b.putInt("key", 1123);
intent.putExtras(b);
...
Android : launching diff activities under TabWidget
I am trying to launch activities under each tab.
I have tried with following code
public class Tab_Proj1 extends TabActivity {
TabHost mTabHost ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Context context = getApplicationContext();
//mTabHost = (TabHost) this.findViewById(R.id.);
mTabHost = getTabHost();
mTabHost.setup();...
Android app with multiple activities
I have a very simple game that consists of only one activity, and I want to add a title screen.
If the title screen is another activity, what changes do I need to make to my manifest file to make the title screen open first?
The gameplay activity is called Leeder, and the title screen activity is called LeederTitleScreen
here is my current manifest file.
<?xml version="1.0" encodi...
xml - Android - Should I use multiple activities or multiple content views
i'm new with android.
I'm working on an application using xml layouts.
I wish to know which is better:
1. Use few activities and change its contentview
2. Use an activity for each 'view' needed
If both works, in which case which option would be better?
thx a lot
android - Sending data between activities within my app?
I have a TabActivity, and the tabs point to sub activities. Is there a way I can send a 'message' to those child activities? I just want to pass a string across, not sure if this is possible.
I have some data being fetched by the parent TabActivity, and the child tabs can't do anything useful until the parent is done fetching. When fetching is complete, I'd like to pass that data to the child activities so they ca...
java - When to use new layouts and when to use new activities?
I'm making a game in Android and I'm trying to add a set of menu screens. Each screen takes up the whole display and has various transitions available to other screens. As a rough summary, the menu screens are:
Start screen
Difficult select screen
Game screen.
Pause screen.
Game over screen.
And there are several different ways you can transition between scre...
Still can't find your answer? Check out these communities...
Android Google Support | Android Community | Android Community (Facebook) | Dev.io Android