Right place for putting mp3 files in an android project

北慕城南 提交于 2019-12-29 02:51:06

问题


Is there any folder like res/drawable for mp3 or generally audio files? If yes, what is it and how can I get access to it from the app?


回答1:


The best place to put such .mp3 or any other files would be in the assets folder.

These files once stored will become a part of your android app itself and can be read easily. This tutorial describes it well.

 AssetFileDescriptor afd = getAssets().openFd("AudioFile.mp3");
 MediaPlayer player = new MediaPlayer();
 player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
 player.prepare();
 player.start();

Alternatively you can also store it in the raw folder and read it directly by specifying the path as the raw folder. this can be played as:

int resID=getResources().getIdentifier(fname, "raw", getPackageName());
MediaPlayer mediaPlayer=MediaPlayer.create(this,resID);



回答2:


Here are some steps you can easily follow.

Step-1: Open the android studio with the project in which you want to add-on audio clip/media file. Step-2: Create a raw folder. Step-3: Add media file to raw folder by simply copy and paste that to raw folder.

Step-4: Here we added a media file “ring.mp3” . Now open the Java File of desired activity, here we are adding audio in MainActivity.

Step 5: Further add this code.

MediaPlayer ring= MediaPlayer.create(MainActivity.this,R.raw.ring);
    ring.start();

**Step 6: Now run the App and you will music will play when App will start

**




回答3:


Place it into your assets folder. Preferably under assets/raw/myfile.mp3 You can access it using:

String mp3File = "raw/music.mp3";
AssetManager assetMan = getAssets();
MediaPlayer media = new MediaPlayer();
FileInputStream mp3Stream = assetMan.openFd(mp3File).createInputStream();
media.setDataSource(mp3Stream.getFD());
media.prepare();
media.start();



回答4:


You should save the .mp3 into res/raw. AndroidStudio recognizes the raw folder. (By contrast, it does not automatically recognize a res/assets folder).

To play music.mp3:

mediaPlayer = MediaPlayer.create(ctx, R.raw.cat_meow); mediaPlayer.start();

Note the convenient use of R. syntax.



来源:https://stackoverflow.com/questions/10959554/right-place-for-putting-mp3-files-in-an-android-project

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!