简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM