Play multimedia files located in the resource folder

I currently have a set of media files in the source folder of an Android project that load and play quickly when called using the mediaplayer class. I need to add more variants of these files and classify them into folders, but apparently the raw folder does not support folders. Will I be able to quickly download these files from the resource folder and play them using the media player? If so, how?

+4
source share
3 answers

I have this method that returns all files by extension to a folder inside the resource folder:

public static String[] getAllFilesInAssetByExtension(Context context, String path, String extension){ Assert.assertNotNull(context); try { String[] files = context.getAssets().list(path); if(StringHelper.isNullOrEmpty(extension)){ return files; } List<String> filesWithExtension = new ArrayList<String>(); for(String file : files){ if(file.endsWith(extension)){ filesWithExtension.add(file); } } return filesWithExtension.toArray(new String[filesWithExtension.size()]); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } 

if you call it using:

 getAllFilesInAssetByExtension(yourcontext, "", ".mp3"); 

this will return all my mp3 files in the root folder with resources.

if you call it using:

 getAllFilesInAssetByExtension(yourcontext, "somefolder", ".mp3"); 

it will search in "somefolder" for mp3 files

Now that you have a list of all the files you are opening, you will need the following:

 AssetFileDescriptor descriptor = getAssets().openFd("myfile"); 

To play the file, simply do:

 MediaPlayer player = new MediaPlayer(); long start = descriptor.getStartOffset(); long end = descriptor.getLength(); player.setDataSource(this.descriptor.getFileDescriptor(), start, end); player.prepare(); player.setVolume(1.0f, 1.0f); player.start(); 

Hope this helps

+6
source

Here is a function that can play media files from the folder of your resource. And you can use it with smth, like play(this,"sounds/1/sound.mp3");

 private void play(Context context, String file) { try { AssetFileDescriptor afd = context.getAssets().openFd(file); meidaPlayer.setDataSource( afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength() ); afd.close(); meidaPlayer.prepare(); meidaPlayer.start(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } 
+5
source

You can put your mp3 files in res / raw folder as myringtone.mp3 or as you wish.

 MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.myringtone); mediaPlayer.start(); 
0
source

Source: https://habr.com/ru/post/1380936/


All Articles