Read audio file from assets on Android - android

I am trying to play audio files stored in the assets directory, but before I even read a file I get the error "error occured java.io.FileNotFoundException: track.mp3". Here's how I read it:
AssetFileDescriptor afd = getAssets().openFd("track.mp3");
I read a lot of descriptions on the internet, but no success.

I think this code should work for you:
AssetFileDescriptor afd = getAssets().openFd("track.mp3");
MediaPlayer player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
player.prepare();
player.start();
Otherwise, check if the file is in the right folder and the name is "track.mp3".

Right-click your "track.mp3" file, with the "Refactor" > "Move" command, move your file to another directory (e.g. "res"). With this same command, move it back to your "assets" directory. For me, it works.

Android guidelines suggest for Audio use res/raw folder. So make sure that all audio are there and when you read you can use this method:
void playAudio(Context mContext, String sound){
new AudioPlayer().play(mContext, mContext.getResources().getIdentifier(
sound,"raw", mContext.getPackageName()));
}
And if you need something line audio player then take a look at MediaPlayer

Use this code
MediaPlayer mediaPlayer = new MediaPlayer();
AssetFileDescriptor afd;
try {
afd = getAssets().openFd("1.mp3");
mediaPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
Toast.makeText(LearnActivity.this, "Error Playing audio from Asset directory",Toast.LENGTH_SHORT).show();
}
Otherwise, check if the file is in the right folder and the name is "track.mp3".

Related

play mp3 file in resource folder not working

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();

Android APK Expansion File, Cannot read .wav files

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.

Streaming music and save cache file on local on Android

I use below code to play streaming music:
try {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
mediaPlayer.start();
}
catch(Exception e) {
e.printStackTrace();
}
I want to buffering file to local cache file at the same time.
And next time want to play this url music can play the local file directly.
How can I do it?
Or anyone can provide references?

getFileDescriptor returns null while reading mp3 files from the expansion files

I have downloaded and stored the expansion files successfully.But it crashes when i try to play the mp3 inside..
ZipResourceFile expansionFile = APKExpansionSupport.getAPKExpansionZipFile(getApplicationContext(),
1, 0);
InputStream fileStream = expansionFile.getInputStream("mysong.mp3");
AssetFileDescriptor asd = expansionFile.getAssetFileDescriptor("mysong.mp3");
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(asd.getFileDescriptor(), asd.getStartOffset(), asd.getLength());
asd.close();
mediaPlayer.prepare();
mediaPlayer.start();
Here the logcat says both the inputstream and the file descriptor are null..Can anyone help me ?
Finaly it solved.. The file name should be with the full path..
AssetFileDescriptor asd = expansionFile.getAssetFileDescriptor("main.1.com.mypackage.app/mysong.mp3");

Intent to play video on Android from file on SD Card

I'm trying to load an intent to play a video file on my phone's SD drive. I'm not sure what I'm doing wrong...
String movieurl = Environment.getExternalStorageDirectory() + "/Videos/Wildlife.wmv";
Intent intentToPlayVideo = new Intent(Intent.ACTION_VIEW);
intentToPlayVideo.setDataAndType(Uri.parse(movieurl), "video/*");
startActivity(intentToPlayVideo);
I get an error "File cannot be displayed of played".
Any thoughts?
Note:
I've also tried:
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(movieurl);
mp.prepare();
mp.start();
Which fails with exception: java.io.IOException: Prepare failed.: status=0x1
Figured it out...
Turns out that on the Droid X2, Environment.getExternalStorageDirectory() returns "/mnt/sdcard", which isn't actually the SD Card.
(Found this out by doing a File.listFiles())
The actual SD Card directory on the Droid X2 is "/mnt/sdcard-ext".
Thanks for the help!
Does the WMV file play by itself in the standard media player? I'd suspect if you continue to get errors that perhaps the file is just not playable.
Try like this:
FileInputStream fis = new FileInputStream(new File(movieurl));
MediaPlayer mp = new MediaPlayer();
mediaPlayer.setDataSource(fis.getFD());
fis.close();
mp.prepare();
mp.start();

Categories

Resources