Playing Audio from Cache Directory - android

When playing audio from sdcard, MediaPlayer plays the file. But when playing from getCacheDir() it is an error. Is my conclusion right that MediaPlayer can't play files from getCacheDir() ?
Here's a code snippet:
private void startPlaying(String asAudioFileName) {
File fFile = new File(VocaPreview.this.getCacheDir() + "/" + asAudioFileName.toLowerCase() + ".mp3");
if(!fFile.isFile()) {
Toast.makeText(getApplicationContext(), "File not found", Toast.LENGTH_SHORT).show();
} else {
try {
FileInputStream fisAudio = new FileInputStream(fFile);
//fmpAudio.setDataSource(VocaPreview.this.getCacheDir() + "/" + asAudioFileName.toLowerCase() + ".mp3");
//fmpAudio.setDataSource("/sdcard/2.mp3");
fmpAudio.setDataSource(fisAudio.getFD());
fmpAudio.prepare();
fmpAudio.start();
} catch(IOException ioe) {
Log.e("START PLAYING", ioe.getMessage());
}
}
}

UPDATE:
I just read from this Blog and solved my problem, inorder for me to play audio inside a cache, I added this line and that's it. Hope this helps anyone in the future. Here is the method.
File file = new File(filepath)
file.setReadable(true, false);

Here's a function that also works on API levels < 9:
Runtime.getRuntime().exec("chmod 644 "+ outputFile.getAbsolutePath());

Related

invoke audio recorder with intent and save voice in sdcard

I try call the default audio recorder with intent and send path to audio recorder than save voice in my path in sdcard.I use this code:
File audioFile = new File(Environment.getExternalStorageDirectory().getPath() + "/nabege" + File.separator + "audio"
+ File.separator + System.currentTimeMillis() + ".amr");
Uri audioUri = Uri.fromFile(audioFile);
record_audio_Intent.putExtra(MediaStore.EXTRA_OUTPUT, audioUri);
startActivityForResult(record_audio_Intent, 0);
This app save voice in default path. This path (nabege/audio) created in sdcard and exist.Please help
Sound recording via intent always saves the recorded file to root of sdcard (or to a default path). Also, this intent may not be supported in certain phone models.
You must use MediaRecorder directly if you want to save recorded files to your custom paths.
Like this:
MediaRecorder recorder = null;
private void startRecording(File file) {
if (recorder != null) {
recorder.release();
}
recorder = new MediaRecorder();
recorder.setAudioSource(AudioSource.MIC);
recorder.setOutputFormat(OutputFormat.THREE_GPP);
recorder.setAudioEncoder(AudioEncoder.AMR_WB);
recorder.setOutputFile(file.getAbsolutePath());
try {
recorder.prepare();
recorder.start();
} catch (IOException e) {
Log.e("giftlist", "io problems while preparing [" +
file.getAbsolutePath() + "]: " + e.getMessage());
}
}

save to file stopped working

First of all here's the code so everybody knows what we're dealing with:
try
{
// now save to external files
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
String fileName = CONSTANTS.SETTINGS.MANAGER.DEFAULT_FILE_NAME + "." + this.format.value();
File saveDir = new File(CONSTANTS.SETTINGS.MANAGER.EXTERNAL_PUBLIC_DIR + File.separator + this.projectName);
if (saveDir.mkdirs() || saveDir.isDirectory())
{
File saveFile = new File(saveDir.getAbsolutePath() + File.separator + fileName);
File saveFileRoot = new File(CONSTANTS.SETTINGS.MANAGER.EXTERNAL_PUBLIC_DIR + File.separator + "Survey-" + projectName + ".xml");
LayerManager.getInstance().setDate(new Date());
switch (format)
{
case XML:
{
if (CONSTANTS.DEBUGGING_MODE)
{
SLog.d(CONSTANTS.SETTINGS.MANAGER.LOGTAG, "Writing user file into " + saveFile.getAbsolutePath());
}
xmlSerializer.write(LayerManager.getInstance(), saveFile);
xmlSerializer.write(LayerManager.getInstance(), saveFileRoot);
}
break;
case JSON:
{
FileWriter saveWriter = new FileWriter(saveFile);
try
{
if (CONSTANTS.DEBUGGING_MODE)
{
SLog.d(CONSTANTS.SETTINGS.MANAGER.LOGTAG, "Writing user file into " + saveFile.getAbsolutePath());
}
String content = gson.toJson(LayerManager.getInstance());
saveWriter.write(content);
}
finally
{
saveWriter.flush();
saveWriter.close();
}
}
break;
default:
{
SLog.e(CONSTANTS.ACTIVITY.MAIN.LOGTAG, "No user save requested.");
}
break;
}
// send event to update media scanner
FileSaved event = new FileSaved();
EventBus.getDefault().post(event);
}
else
{
SLog.e(CONSTANTS.ACTIVITY.MAIN.LOGTAG, "Could not write into save projectName");
return false;
}
}
else
{
return false;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return true;
}
This works perfectly on an android 4.1.2 device API 16.
The code creates a new diretory, named any value projectName holds, in the "external_public_dir" <= saveDir
Then, depending on format xml/json, in both cases the file is written in the newly created directory.
As a test the file is also directly written to external_public_dir.
When you attach the device to your (windows) computer the files/directories are where they should be.
However, when this code is run on a device with Android 4.4.4 API 19 the two directories are not recognized anymore by windows... .
The two 'files' test & test2 should be folders containing an xml file each.
And the following makes the problem even more confusing:
1)The Android File explorer DOES recognize the directories...
2)As you can see, the other file created by saveFileRoot does appear in windows explorer...
I am stumped, any suggestions or tips would be very helpful!
Thanks in advance

Android incompeted download file

I try to download audio from a URL. I use following sample download manager code from Github https://github.com/folee/Download_Mgr
My problem is If i cancel download, Incomplete mp3 file still there in SDcard. How can i remove Incomplete mp3 files?
#Override
public void onClick(View v) {
Intent downloadIntent = new Intent(DownloadValues.Actions.DOWNLOAD_SERVICE_ACTION);
switch (v.getId()) {
case R.id.btn_continue:
// mDownloadManager.continueTask(mPosition);
downloadIntent.putExtra(DownloadValues.TYPE, DownloadValues.Types.CONTINUE);
downloadIntent.putExtra(DownloadValues.URL, url);
mContext.startService(downloadIntent);
mViewHolder.continueButton.setVisibility(View.GONE);
mViewHolder.pauseButton.setVisibility(View.VISIBLE);
break;
case R.id.btn_pause:
// mDownloadManager.pauseTask(mPosition);
downloadIntent.putExtra(DownloadValues.TYPE, DownloadValues.Types.PAUSE);
downloadIntent.putExtra(DownloadValues.URL, url);
mContext.startService(downloadIntent);
mViewHolder.continueButton.setVisibility(View.VISIBLE);
mViewHolder.pauseButton.setVisibility(View.GONE);
break;
case R.id.btn_delete:
// mDownloadManager.deleteTask(mPosition);
downloadIntent.putExtra(DownloadValues.TYPE, DownloadValues.Types.DELETE);
downloadIntent.putExtra(DownloadValues.URL, url);
mContext.startService(downloadIntent);
removeItem(url);
break;
}
}
my file bath :
public class ConfigUtils {
public static void InitPath(Context ctx) {
File temFile = Environment.getExternalStorageDirectory();
if (temFile != null && temFile.canWrite() && Util.getAvailableExternalMemorySize() > 0) {
IMG_PATH = Environment.getExternalStorageDirectory().getPath() + "/DL_Mgr/Image/";
FILE_PATH = Environment.getExternalStorageDirectory().getPath() + "/DL_Mgr/Downloads/";
}
else {
IMG_PATH = ctx.getFilesDir() + "/Image/";
FILE_PATH = ctx.getFilesDir() + File.separator;
}
new File(IMG_PATH).mkdirs();
new File(FILE_PATH).mkdirs();
Log.i(TAG, "IMG_PATH-->" + IMG_PATH + "\n FILEPATH-->" + FILE_PATH);
}
}
I use this code for delete temp files but not work
case R.id.btn_delete:
File tempFile = new File(ConfigUtils.FILE_PATH + "filename".toString());
if(tempFile.exists()) {
tempFile.delete();
}
But it not work
EDIT:
WORKING CODE: (If download mp3 temp file remane like : "sample.mp3.download"
so ichanged code like this it work fine
File tempFile = new File(ConfigUtils.FILE_PATH + filename +".download".toString());
if(tempFile.exists()) {
tempFile.delete();
}
Before downloading starts. You must know where you are saving the file. So probably a absolute path or Uri pointing to a file in sdcard
that you are giving to Download manager to store your file at.
Incase of cancel. create a file object from that uri or absolute path and call delete on file object if exists.
Something like this
File tempFile = new File(uri.toString());
if(tempFile.exists()) {
tempFile.delete();
}
This should be simple. Google it out

Android MediaPlayer: Play Audio Resource in Raw Based on URI

The problem I am trying to solve is in an activity that needs to play back audio files. Most of the files will be user created (and saved into external storage), and therefore played with the following code (based on Google's example code):
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setDataSource(filename);
mPlayer.prepare();
mPlayer.start();
Some of the audio files, though, are going to be included with the app, are usually played with the following code:
MediaPlayer mPlayer = MediaPlayer.create(getBaseContext(), R.raw.filename);
mPlayer.prepare();
mPlayer.start();
The issue is that I would like to be able to play the audio files in the raw folder in the same way that I am playing the user created files since I don't necessarily know which will be needed. I tried tried to get the URI of the audio file in the raw folder and play it with the following code:
Uri uri = Uri.parse("android/resource://com.my.package/" + R.raw.filename);
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setDataSource(uri.toString());
mPlayer.prepare();
mPlayer.start();
But nothing happens. No error messages, no playing audio.
I outlined what I thought was the simplest solution, but I am willing to go another route if it accomplishes the task. Any assistance is greatly appreciated.
I've managed to get it working, here is the code I used.
mMediaPlayer = new MediaPlayer();
Uri mediaPath = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.filename);
try {
mMediaPlayer.setDataSource(getApplicationContext(), mediaPath);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
I see two problems I see with your code. The first is that "android/resource" needs to become "android.resource"
The second is that setDataSource(String) won't work in this case due to the fact that you need context to use raw files as otherwise it tries to open the file incorrectly. (See the top answer in MediaPlayer.setDataSource(String) not working with local files)
final int[] song = {R.raw.letmeloveyou,R.raw.aarti,R.raw.answer};
final MediaPlayer mp = new MediaPlayer();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
if (true == mp.isPlaying()) {
mp.stop();
mp.reset();
Toast.makeText(getBaseContext(), "Again Playing", Toast.LENGTH_LONG).show();
mp.setDataSource(Result.this, Uri.parse("android.resource://" + getPackageName() + "/" + song[position]));
mp.prepare();
mp.start();
} else {
Toast.makeText(getBaseContext(), "Playing", Toast.LENGTH_LONG).show();
mp.setDataSource(Result.this, Uri.parse("android.resource://" + getPackageName() + "/" + song[position]));
mp.prepare();
mp.start();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(),e.toString(),Toast.LENGTH_LONG).show();
}
}
});
When I used toString() in Uri it failed, when I used direct Uri it played well.
Uri musicUri = Uri.parse("android.resource://" + context.getPackageName() + "/" + resourceID);
Log.d(TAG, "musicUri: " + musicUri);
mediaPlayer.setDataSource(context, musicUri);

file.mkdirs() not working

i want to write to a file in the sdcard of my phone.i used the below code to do this.
private CSVWriter _writer;
private File _directory;
public String _fileTestResult;
private String PATH_FILE_EXPORT = "/applications/foru/unittestframework/";
public ExportData(){
_writer=null;
_directory = new File(Environment.getExternalStorageDirectory () +PATH_FILE_EXPORT);
if(!_directory.exists())
_directory.mkdirs();
}
public void exportResult(String testcaseNum,String testcase,String status){
try {
if(_directory.exists()){
//do something
}
but mkdirs() is not working.so i could not excecute following code in the if condition.please help me.
note:i have given the permission in manifest file.
EDIT:
i am using this file write option for storing the result of automation testing using robotium.i have created a normal project and tried to create directory in sdcard.but the same code when i am using in this testproject it is not working.why like that?dont unit testing framework support this?
have you add the correct permission in your manifest ?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Edit : ok, i just read your note for permission.
If it's help you this is my sdcard cache code :
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
String evtDir = "";
if(evt > 0){
evtDir = File.separator + evt;
}
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory()
+ File.separator
+ "Android"
+ File.separator
+ "data"
+ File.separator
+ Application.getApplicationPackageName()
+ File.separator + "cache"
+ evtDir);
}else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
}
Try below code
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()) {
imagefolder = new File(root,
mycontext.getString(R.string.app_name));
imagefolder.mkdirs();
}
} catch (Exception e) {
Log.e("DEBUG", "Could not write file " + e.getMessage());
}
Try with:
if(!_directory.exists())
_directory.mkdir();
Also check this - Creating a directory in /sdcard fails

Categories

Resources