1

I'm using the BackgroundSoundService for playing music in a background of my activity. However, when I switch to another activity, I would like to use another sound. This is how my class looks like. I need to change that "R.raw.sound" programmatically.

public class BackgroundSoundService extends Service {
    MediaPlayer mediaPlayer;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = MediaPlayer.create(this, R.raw.sound);
        mediaPlayer.setLooping(true); // Set looping
        mediaPlayer.setVolume(100, 100);
    }
    public int onStartCommand(Intent intent, int flags, int startId) {
        mediaPlayer.start();
        return startId;
    }
    @Override
    public void onDestroy() {
        mediaPlayer.stop();
        mediaPlayer.release();
    }
    @Override
    public void onLowMemory() {
    }} 
tomerpacific
  • 4,704
  • 13
  • 34
  • 52
sznn
  • 11
  • 1
  • Have you thought of exposing a method that creates a new media player with the desired sound file? – tomerpacific Mar 20 '22 at 10:22
  • If you don't want to expose a method then you can use a broadcast receiver in this mediaplayer service . Then send the broadcast from any part of the app and change the sounds accordingly . – Muhammad Ahsan Mar 20 '22 at 10:51

0 Answers0