14

I want to play background sound in my app which I made. Help me how can I do this?...Here is the entire code.

public class Numbers extends Activity {
    public static MediaPlayer mp = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_numbers);
        ViewPager viewPager = (ViewPager)findViewById(R.id.view_pager);
        ImagePagerAdapter adapter = new ImagePagerAdapter();
        viewPager.setAdapter(adapter);
    }

    private class ImagePagerAdapter extends PagerAdapter {
        private int[] mImages = new int[]{R.drawable.no1,R.drawable.no2,R.drawable.no3,R.drawable.no4,R.drawable.no5,R.drawable.no6,R.drawable.no7,R.drawable.no8,R.drawable.no9};

        @Override
        public int getCount() {
            return mImages.length;
        }
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == ((ImageView) object);
        }
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Context context = Numbers.this;
            ImageView imageView = new ImageView(context);
            int padding =context.getResources().  
            getDimensionPixelSize(R.dimen.activity_vertical_margin);
            imageView.setPadding(padding, padding, padding, padding);
            imageView.setScaleType(ImageView.ScaleType.CENTER);
            imageView.setImageResource(mImages[position]);
            ((ViewPager) container).addView(imageView, 0);

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                ((ViewPager) container).removeView((ImageView) object);
            }
        }
    }//end of sub-class ImagePagerAdapter
}//End of Numbers class

Just tell me what I need to add in this code to play background music which will be in loop mode till the app runs.

TheMohanAhuja
  • 1,855
  • 2
  • 19
  • 30
SuRaj Creator
  • 945
  • 1
  • 9
  • 25

4 Answers4

22

This is tested in android studio 2.2.3

1) first copy and paste your music.mp3 into app.res.raw.

2) set service into AndroidManifest.xml be like this:

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    :
    :
    <service android:name=".SoundService"  android:enabled="true"></service>
</application>

3) Add SoundService.java file with contain this code:

package com.jahanweb.ring;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

public class SoundService extends Service {
    MediaPlayer player;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void onCreate() {
        player = MediaPlayer.create(this, R.raw.music); //select music file
        player.setLooping(true); //set looping
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        player.start();
        return Service.START_NOT_STICKY;
    }

    public void onDestroy() {
        player.stop();
        player.release();
        stopSelf();
        super.onDestroy();
    }

}

4) use it in the activity be like this:

package com.jahanweb.ring;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //start service and play music
        startService(new Intent(MainActivity.this, SoundService.class));

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    protected void onDestroy() {
        //stop service and stop music
        stopService(new Intent(MainActivity.this, SoundService.class));
        super.onDestroy();
    }
}
Nabi K.A.Z.
  • 9,887
  • 6
  • 59
  • 81
  • I have SplashScreen class for a game where music starts. Then this screen changes to others screens and game begins. I still want music to be in behind (and it really is) but when I minimize game music still plays, so only way to stop it is by killing app in task manager. How to fix this? – Raskoljnikovic Jan 31 '21 at 18:42
  • @Raskoljnikovic maybe if you open new question was better. – Nabi K.A.Z. May 03 '21 at 03:13
18

Better to put your media code in service. It is best way to play media in background.

public class serv extends Service{

    MediaPlayer mp;
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    public void onCreate()
    {   
        mp = MediaPlayer.create(this, R.raw.b);
        mp.setLooping(false);
    }
    public void onDestroy()
    {       
        mp.stop();
    }
    public void onStart(Intent intent,int startid){

        Log.d(tag, "On start");
        mp.start();
    }
}

where raw is folder created in resources. and R.raw.b is an mp3 file.

TheMohanAhuja
  • 1,855
  • 2
  • 19
  • 30
Ravi
  • 34,851
  • 21
  • 122
  • 183
  • 3
    How is this being invoked from Activity? – Si8 Dec 13 '16 at 19:21
  • is it possible to play an audio in background which is received from API instead of from raw folder? – SKK Sep 09 '20 at 12:58
  • What I want to do is, The user will open my app. The app will listen something from server. If the server sends audio, the app should play it even its screen locked. Is it possible? – SKK Sep 09 '20 at 13:03
5
MediaPlayer  player = MediaPlayer.create(this,  R.raw.music);
player.setLooping(true); // Set looping
player.setVolume(100,100);

public int onStartCommand(Intent intent, int flags, int startId) {
    player.start();
    return 1;
}

@Override
public void onDestroy() {
    player.stop();
    player.release();
}

public void onStart(Intent intent, int startId) 
{
    // TODO
}
TheMohanAhuja
  • 1,855
  • 2
  • 19
  • 30
  • I tried your setVolume command in the example above of @nabi-k-a-z, but it has no effect. I solved it with this: https://stackoverflow.com/a/12197453/1069083 – rubo77 May 19 '19 at 22:58
1

Try below link... hope this will work

How to play audio in android using android service

TheMohanAhuja
  • 1,855
  • 2
  • 19
  • 30
Riskhan
  • 4,434
  • 12
  • 50
  • 76