0

If someone can help me with this problem: I'm trying to get the song from res folder in this method

    private void playSound(String file) {
        Context context = binding.playBtn.getContext();
        Resources resources = context.getResources();
        int sound_id = resources.getIdentifier(file,"raw",
                context.getPackageName());
       MediaPlayer mediaPlayer = MediaPlayer.create(context,sound_id);
       mediaPlayer.start();
    }

Then to call this method here

    public void bind(CalmScreenItem calmScreenItem) {
        binding.mainText.setText(calmScreenItem.mainText);
        binding.subtext.setText(calmScreenItem.subtext);
        binding.itemImg.setImageDrawable(getImage(calmScreenItem.imgUrl));
        binding.container.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                playSound(calmScreenItem.soundUrl);
            }
        });
    }

Then finally call in the main fragment in the list**

private List<CalmScreenItem> getItems() {
    List<CalmScreenItem> calmScreenItems = new ArrayList<>();
    calmScreenItems.add(new CalmScreenItem(getString(R.string.main_item1),getString(R.string.sub_item1),"guide","free.mp3"));
    calmScreenItems.add(new CalmScreenItem(getString(R.string.main_item2),getString(R.string.sub_item2),"mindfull","mindfull.mp3"));


    return calmScreenItems;
}

The output should be when clicked on button to play different sound from the res folder

Can someone please help me! Thanks

  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Mar 24 '22 at 21:33

1 Answers1

0

There is a mistake in the way you are fetching the files

YOu would need to use an Uri and pass that to the MediaPlayer for it to be able to play your music . Also store y our audio files in raw subdirectory

For eg:

Uri mediaPath = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.filename);
try {
    mMediaPlayer.setDataSource(getApplicationContext(), mediaPath);
    mMediaPlayer.prepare();
    mMediaPlayer.start();
} catch (Exception e) {
    e.printStackTrace();
}

Ref : StackOverflow questionon playing music from raw resource

Narendra_Nath
  • 4,578
  • 3
  • 13
  • 31