Julio Ensutias
Julio Ensutias

Reputation: 122

play Mp3 Intent Android Studio

I have callintent() method in MainActivity:

public void callintent (View view){
    Intent i = new Intent (this, DetailActivity.class);
    i.putExtra("string", "String Text");
    i.putExtra("img", R.drawable.icon);
    startActivity(i);
}

that method is set string and image for DetailActivity

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);

    Intent i = getIntent();
    String string = i.getStringExtra("string");

    TextView textview = (TextView) findViewById(R.id.text);
    textview.setText(string);

    ImageView imageView = (ImageView) findViewById(R.id.image);
    imageView.setImageDrawable(getResources().getDrawable(getIntent().getIntExtra("img",0)));
}

i was successfuly display text and image in DetailActivity but now i want add mp3 file for play in DetailActivity where the file is set in MainActivity,

Please Help Me, Thank you

-- Edited --

i can play mp3 with add this in MainActivity

i.putExtra("selectedMp3",R.raw.file);

and add this in DetailActivity

int mp3 = getIntent().getIntExtra("selectedMp3", 0);
final MediaPlayer mp = MediaPlayer.create(this, mp3);
mp.start();

but sound still playing when backpress or go to homescreen, how can i stop sound when backpress or go to homescreen,

Upvotes: 2

Views: 3130

Answers (3)

Manoj kumar
Manoj kumar

Reputation: 470

There are 2 ways to play an audio or mp3 file.

  1. Using Intents and playing them outside the app:

    Intent i = new Intent();  
    i.setAction(android.content.Intent.ACTION_VIEW);  
    intent.setDataAndType(Uri.fromFile(new File(path)), "audio/*");  
    startActivity(i);
    

If you use this method and if the android SDK version for build Gradle is greater than 23 u must use the FileProvider to give permission to access file outside the application. The flag and action will be like below:

i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
i.setDataAndType(FileProvider.getUriForFile(this,BuildConfig.APPLICATION_ID + ".provider",file), "audio/*");
  1. Using Media Player and playing them with in the app and add the relevant permission in the manifest:

    MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.example); mPlayer.start();

Upvotes: 5

Harshit Trivedi
Harshit Trivedi

Reputation: 782

Intent in = new Intent();  
in.setAction(android.content.Intent.ACTION_VIEW);  
File file = new File(File_Path);  
intent.setDataAndType(Uri.fromFile(file), "audio/*");  
startActivity(in);

Upvotes: 1

Girish H
Girish H

Reputation: 79

Step 1 : Put your mp3 file in raw folder

Step 2 : Call below MediaPlayer code in DetailActivity

MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.example);
mPlayer.start();

Upvotes: 2

Related Questions