How to play the audio files directly from res/raw

2019-01-14 05:45发布

问题:

I have multiple audio files in res/raw folder. I showing ListView that contains audio files name. I want to play the corresponding audio file when user select into the ListView. I have used setDataSource(path), but it showing error while playing. How play the audio files directly from that folder? Or Is there any other way?

回答1:

add this code in onItemClickListener.

listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int position,long id) {                 
                TextView txtView=(TextView)view.findViewById(R.id.txt_view);
                String fname=txtView.getText().toString().toLowerCase();

                                int resID=getResources().getIdentifier(fname, "raw", getPackageName());

                              MediaPlayer mediaPlayer=MediaPlayer.create(this,resID);
                    mediaPlayer.start();
            }
        });


回答2:

try this for playing from raw ::

MediaPlayer mPlayer2;
mPlayer2= MediaPlayer.create(this, R.raw.bg_music_wav);
        mPlayer2.start();

permission in manifest file ::

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

Update::

public void onItemClick(AdapterView<?> arg0, View view, int position,long id) {     
  MediaPlayer mPlayer2;
if(position==1)
{
    mPlayer2= MediaPlayer.create(this, R.raw.song1);
            mPlayer2.start();
}else it() .....
}


回答3:

mVideoView = (VideoView) findViewById(R.id.Video_FrontPage);
uri = Uri.parse("android.resource://com.urPackageName/" + R.raw.welcom_video);
mVideoView.setVideoURI(uri);
mVideoView.setMediaController(new MediaController(this));
mVideoView.requestFocus();
mVideoView.start();

Hope this may helps you.



回答4:

 lv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> parent, View view,
          int position, long id) {

          // selected item 
          String product = ((TextView) view).getText().toString();

          int [] resID= {R.raw.sound1,R.raw.sound2,R.raw.sound3};
        MediaPlayer mediaPlayer=MediaPlayer.create(this,resID[position]);

          mediaPlayer.start();
          // sending data to new activity


      }
    });
}