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 {
pu
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.
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();
}
}
Try below link... hope this will work
How to play audio in android using android service
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
}