I currently have a set of media files in the raw folder of the android project that are loaded quickly and played when called using the mediaplayer class. I need to add more variations of these files and categorize them into folders, but apparently the raw folder does not support folders. Would I be able to quickly load these files from the assets folder and play them with mediaplayer? If so, how?
I've this method that returns the all files by extension in a folder inside asset 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 of assets folder.
if you call it using:
getAllFilesInAssetByExtension(yourcontext, "somefolder", ".mp3");
this will search in "somefolder" for mp3 files
Now that you have list all files to open you will need this:
AssetFileDescriptor descriptor = getAssets().openFd("myfile");
To play the file just 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
Here is a function that can play mediafiles from your asset folder. 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();
}
}
You could put your mp3 files at : res/raw folder as myringtone.mp3 or as your wish.
MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.myringtone);
mediaPlayer.start();
Related
I want to play an mp3 file in my res/raw folder.
But i get error as "error (1, -2147483648)" and IOException on mp.prepare()
My code
try {
MediaPlayer mPlayer = MediaPlayer.create(NavigationHome.this, R.raw.notfy);
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
I also tried with
try {
mp.setDataSource(NavigationHome.this, Uri.parse("android.resource://com.hipay_uae/res/raw/notfy"));
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
Another solution that I tried
AssetFileDescriptor afd = getAssets().openFd("AudioFile.mp3");
MediaPlayer player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.prepare();
player.start();
These too didn't work for me.
It will help more if you can post the StackTrace in your question.
But, as per the information in your question, the below code should work for playing the media file from the raw resource folder.
If you use the create() method, prepare() gets called internally and you don't need to explicitly call it.
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.notify);
mediaPlayer.start();
But, the point to consider is that prepare() generally throws an IllegalStateException, and in your case, you are getting an IOException. So it would be worth checking if the file is in fact present in raw folder and/or the file is corrupt.
Try to initialize your media player before preparing it or setting data source to it
Play From external directory
String filePath = Environment.getExternalStorageDirectory()+"/folderName/yourfile.mp3";
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();
mediaPlayer.start()
From raw folder
MediaPlayer mediaPlayer = MediaPlayer.create(MainActivity.this,R.raw.song);
mediaPlayer.start();
Try this
String fname="your_filename";
int resID=getResources().getIdentifier(fname, "raw", getPackageName());
MediaPlayer mediaPlayer=MediaPlayer.create(this,resID);
mediaPlayer.start();
I have been developing an App which need to play sounds and have large set of sounds files in .wav format that boast arounds near 1GB size. I have followed the official documentation for making the Expansion file.
First i made a .zip file with 0 compressions, all .wav files are under that files (without any subfolder. that is main.1.package contains all the sounds file).Then i renamed the .zip folder into .obb. After that i put that .obb file inside the apps folder under shared storage obb folder (com.moinul.app is my package name, so the folder name was it, also the expansion file were named main.1.com.moinul.app.obb )
Problem is when i try to read the files from my expansion files i get null pointer exceptions:
try
{
String param = (String) v.getTag();
ZipResourceFile expansionFile = APKExpansionSupport.getAPKExpansionZipFile(context, 1, 0);
AssetFileDescriptor fd = expansionFile.getAssetFileDescriptor("p25_1.wav");
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(fd.getFileDescriptor());
mPlayer.prepare();
mPlayer.start();
}
catch (Exception e)
{
Log.w(TAG, e.getMessage() + "");
e.printStackTrace();
}
I get exceptions saying that fd is null. Any help would be appreciated.
Thanks
Try use: AssetFileDescriptor fd = expansionFile.getAssetFileDescriptor("assets/p25_1.wav");
Try
`public class Test extends Activity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String TAG = "Test";
Context context = this;
try {
MediaPlayer mediaPlayer = new MediaPlayer();
ZipResourceFile expansionFile = APKExpansionSupport.getAPKExpansionZipFile(context, 1, 0);
AssetFileDescriptor assetFileDescriptor = expansionFile.getAssetFileDescriptor("assets/p25_1.wav");
if (assetFileDescriptor != null) {
final FileInputStream fis = assetFileDescriptor.createInputStream();
if (fis != null) {
mediaPlayer.setDataSource(fis.getFD());
fis.close();
mediaPlayer.prepare();
mediaPlayer.start();
} else {
Log.w(TAG, "/fis: null");
}
}
} catch (Exception e) {
Log.w(TAG, e.getMessage() + "");
}
}
}`
Ok so it worked finally. After changing into :
AssetFileDescriptor fd = expansionFile.getAssetFileDescriptor("Sounds/p25_1.wav");
Its working now. Its weird that i had to add Sounds, which was the folder name before compress (i actually compressed this folder and all .wav are under it). I think the compressor made another subfolder inside the .zip.
Anyway thanks for the help.
While using fragment I'm trying to get audio file from raw folder like this:
mediaPlayer = MediaPlayer.create(this, getResources().getIdentifier(audioFile, "raw", getPackageName()));
I'm getting Cannot resolve method 'getPackageName()' error. How to solve this?
I was able to solve it by writing this code:
String path = "android.resource://"+"com.example.myproject"+"/raw/"+audioFile;
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(getActivity(), Uri.parse(path));
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
On my code I use:
mp = new MediaPlayer();
String filePath = Environment.getExternalStorageDirectory().getPath() + "/mymusic/asong.mp3";
try {
mp.setDataSource(filePath);
} catch (IOException e) {
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
And on the emulator the song.mp3 is played normally. But when I test it on my real device, it gives an error (-38, 0). That means it can not find the path of the song. I connect the usb cable, go to my Computer, GT-I8260 and paste the folder "mymusic" (that contains asong.mp3) under "Card" folder (where an empty folder named "LOST.DIR" is also placed). But why doesn't it work? Thanks a lot
it's card but at least
Environment.getExternalStorageDirectory() + "/mymusic/asong.mp3";
is enough.
Make sure it exists because you may not have the folder created before.
File f = new File(Environment.getExternalStorageDirectory() + "/mymusic");
if (!f.exists()) { f.mkdirs(); }
also make sure that it's not mounted while writing, since it may happen that it is not accessable at all.
Also revalidate that you have setupted the manifests permission to read/write the external storage
I need your help. I tried to play an audio file stored in Assets folder but an error occurred.
Here are my code:
try{
if (player.isPlaying()) {
player.stop();
player.release();
}
}catch(Exception e){
Toast.makeText(this, "an exception occurred", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
try{
AssetFileDescriptor afd = BeeDailyConvo.this.getAssets().openFd("sounds/hello_kr.wma");
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.prepare();
player.start();
}catch(Exception e){
e.printStackTrace();
}
And here are my logcat:
06-16 22:39:53.330: W/MediaPlayer(13490): info/warning (1, 26)
06-16 22:39:53.330: E/MediaPlayer(13490): error (1, -4)
Could you please explain what's wrong with my code?
Thank you in advance
Regards,
Priska
This issue has been SOLVED.
The asset file descriptor must be closed before preparing the player. This is how I solved the problem:
player = new MediaPlayer();
AssetFileDescriptor afd = BeeDailyConvo.this.getAssets()
.openFd("sounds/"+file);
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
afd.close();**//just added this line**
player.prepare();
player.start();
Here you can see all Error codes Media player Error codes
-4 error code indicates you have given invalid arguments.
Put your code in try catch block.
Try Using
try {
AssetFileDescriptor afd = CustomListViewActivity.this.getAssets()
.openFd("sounds/hello_kr.wma");
player.setDataSource(afd.getFileDescriptor());
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Unfortunately there is very little information about MediaPlayer error codes available for some reason. However I suggest you try putting your sound file inside res/raw/ instead of your assets.
EDIT:
Start here with the Using the MediaPlayer section in the developer docs. This will show you how to set up and play the sound properly.
EDIT 2:
turns out that can do it from assets see this question: Play audio file from the assets directory
I don't think that wma files are supported.
http://developer.android.com/guide/appendix/media-formats.html
I noticed that you didn't specify the audioStreamType
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MISIC);
use this way it will solve your problem :)
public void playBeep() {
try {
if (m.isPlaying()) {
m.stop();
m.release();
m = new MediaPlayer();
}
AssetFileDescriptor descriptor = getAssets().openFd("mp3 name.mp3");
m.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
m.prepare();
m.setVolume(1f, 1f);
m.setLooping(true);
m.start();
} catch (Exception e) {
}
}