Manju
Manju

Reputation: 742

Playing audio in android

In My Application im using following code to play audio file

Uri data = Uri.parse("file:/" + songnameandpath);
                intent.setDataAndType(data, "audio/*");

                            PackageManager packageManager = getActivity()
                                    .getPackageManager();
                            List<ResolveInfo> activities = packageManager
                                    .queryIntentActivities(intent, 0);
                            boolean isIntentSafe = activities.size() > 0;




                            if (isIntentSafe) {
                                startActivity(intent);

so now when user clicks on back button audio get stopped what if i want to play audio even if the user presses back button on activity and moreover it has to play in background exactly how audio will in mobiles.

Sample code will helps me a lot. Thanks in advance

Upvotes: 1

Views: 255

Answers (1)

JanBo
JanBo

Reputation: 2943

Have you tried working with media player?

here is the code that worked for me, just delete the on pause/destroy methods or redefine them and you will have sound playing even when the user presses back..

public class MainActivity extends Activity {

    private MediaPlayer mp;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        mp= MediaPlayer.create (this, R.raw.sound); // sound is for example your mp3 song
        mp.start ();      
    }

    protected void onDestroy() {
        super.onDestroy();
        mp.release();
    }

    protected void onPause() {
        super.onPause();
        mp.pause();
    }

    protected void onResume() {
        super.onResume();
        mp.start();
    }

    protected void onStart() {
        super.onStart();
    }

}

update

The MediaPlayer will continue playing file even after the activity is finished unless you explicitly stop it by stop function

Upvotes: 1

Related Questions