I am using the MP4ParserMergeAudioVideo to add a new audio to an MP4 file. The library had said to use .wav file, if i keep a .wav file in the directory and give the name of the audiofile as example.m4a, I get a file not found exception. So I changed the file to a .m4a audio file. The code is given below.
findViewById(R.id.append).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String root = Environment.getExternalStorageDirectory().toString();
Log.e("",""+root);
String audio = root + "/download/"+"mymovieaudio.m4a";
String video = root + "/download/"+"My_Movie.mp4";
String output = root + "/download/ouput.mp4";
mux(video, audio, output);
}
});
The mux function is like this
public boolean mux(String videoFile, String audioFile, String outputFile) {
Movie video;
try {
video = new MovieCreator().build(videoFile);
} catch (RuntimeException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
Movie audio;
try {
audio = new MovieCreator().build(audioFile);
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
Track audioTrack = audio.getTracks().get(0);
video.addTrack(audioTrack);
Container out = new DefaultMp4Builder().build(video);
FileOutputStream fos;
try {
fos = new FileOutputStream(outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
BufferedWritableFileByteChannel byteBufferByteChannel = new BufferedWritableFileByteChannel(fos);
try {
out.writeContainer(byteBufferByteChannel);
byteBufferByteChannel.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
I successfully get the output.mp4 file in my download directory of my device. The problem is that it does not have any audio. Please help. Thanks in advance.
Related
I want to get the attached content of MMS like Image or Video/audio.
First I make this
static void getMmsContent(Context context, ArrayList<Mms> mmsArrayList) {
try {
for (Mms unMms : mmsArrayList) {
ContentResolver contentResolver = context.getContentResolver();
Uri uri = Uri.parse("content://mms/part");
String selection = Telephony.Mms.Part.MSG_ID + "=" + unMms.getId();
Cursor query = contentResolver.query(uri, null, selection, null, null);
if (query != null && query.moveToFirst()) {
do {
String name = query.getString(query.getColumnIndex("name"));
String type = query.getString(query.getColumnIndex("ct"));
String txt = query.getString(query.getColumnIndex(Telephony.Mms.Part.TEXT));
String data = query.getString(query.getColumnIndex(Telephony.Mms.Part._DATA));
if (!type.equals("application/smil")) {
String[] dataMms = {name, type, txt, data};
getContent(context, dataMms, unMms);
}
} while (query.moveToNext());
}
if (query != null) {
query.close();
}
}
} catch (Exception e) {
Log.d("Exception", e.toString());
}
}
This line give me the path to the location of the attached content.
String data = query.getString(query.getColumnIndex(Telephony.Mms.Part._DATA));
/data/user_de/0/com.android.providers.telephony/app_parts/PART_1555841710097_Screenshot_20190421-121445_Chrome1.jpg
So now i want to transform the image to a Bitmap to add it to a zip file.
static private void getContent(Context context, String[] dataMms, Mms unMms){
if (dataMms[1].equals("text/plain")) {
unMms.setCorps(dataMms[2]);
} else {
if ("image/jpeg".equals(dataMms[1]) || "image/bmp".equals(dataMms[1]) ||
"image/gif".equals(dataMms[1]) || "image/jpg".equals(dataMms[1]) ||
"image/png".equals(dataMms[1])) {
unMms.setTypeContenu(dataMms[1]);
Bitmap bitmap = null;
InputStream is = null;
try {
File source = new File(dataMms[3]);
is = new FileInputStream(source);
bitmap = BitmapFactory.decodeStream(is);
} catch (IOException e) {
Log.d("Exception", e.toString());
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
Log.d("Exception", e.toString());
}
}
}
if (bitmap != null) {
File file = new File(context.getApplicationInfo().dataDir + "/files/", dataMms[0]);
OutputStream Fout = null;
try {
Fout = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, Fout);
Fout.flush();
Fout.close();
} catch (FileNotFoundException e) {
Log.d("Exception", e.toString());
} catch (IOException e) {
Log.d("Exception", e.toString());
}
}
}
}
}
But my code Throw a Exception on new FileInputStream(source);
I got this
D/Exception: java.io.FileNotFoundException: /data/user_de/0/com.android.providers.telephony/app_parts/PART_1547316880687_Resized_20190112_191438_9422.jpeg (Permission denied)
I have the permissions and i have require the user permission.
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
So i change my code after the comment of CommonsWare to this :
static private void getContent(Context context, String[] dataMms, Mms unMms) {
if (dataMms[1].equals("text/plain")) {
unMms.setCorps(dataMms[2]);
} else {
if ("image/jpeg".equals(dataMms[1]) || "image/bmp".equals(dataMms[1]) ||
"image/gif".equals(dataMms[1]) || "image/jpg".equals(dataMms[1]) ||
"image/png".equals(dataMms[1])) {
unMms.setTypeContenu(dataMms[1]);
Uri partURI = Uri.parse("content://mms/part/" + dataMms[4]);
InputStream is = null;
Bitmap bitmap = null;
try {
is = context.getContentResolver().openInputStream(partURI);
bitmap = BitmapFactory.decodeStream(is);
} catch (IOException e) {
Log.d("Exception", e.toString());
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
Log.d("Exception", e.toString());
}
}
}
if (bitmap != null) {
File file = new File(context.getApplicationInfo().dataDir + "/files/", dataMms[0]);
OutputStream Fout = null;
try {
file.createNewFile();
Fout = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, Fout);
Fout.flush();
Fout.close();
} catch (FileNotFoundException e) {
Log.d("Exception", e.toString());
} catch (IOException e) {
Log.d("Exception", e.toString());
}
}
}
}
}
The tricky part is this :
Uri partURI = Uri.parse("content://mms/part/" + dataMms[4]);
my dataMms[4] is the id of the MMS Part, I get it from this line I put on getMmsContent() :
String id = query.getString(query.getColumnIndex("_id"));
This column give me the id of the part.
But there is no mention about this column in Android Developer documentation : https://developer.android.com/reference/android/provider/Telephony.Mms.Part.html
So I listed the columns with this code in getMmsContent() and I found it :
for (int i = 0; i < query.getColumnCount(); i++) {
Log.i("Column", query.getColumnName(i));
}
Now It's working !
Background:
I am using three fragments and one activity in my application. Two fragments use recyclerViews and the other uses an expandableListView.
Problem:
I am trying to properly program the onPause(), onResume(), onStop(), and onRestart() methods to save the state of my application when the home, back, or switch views buttons are pressed.
To save the state of the program and load it when it comes back I have created the save() and load() methods in my one and only activity.
//from the end of onCreate
load();
}
#Override
protected void onStart() {
super.onStart();
mRef = new Firebase("https://sure-7856d.firebaseio.com/");
}
#Override
protected void onStop(){
super.onStop();
save();
}
#Override
protected void onPause(){
super.onPause();
save();
}
#Override
protected void onResume(){
super.onResume();
load();
}
#Override
protected void onRestart(){
super.onRestart();
load();
}
In the save method I get the adapters from my 2 recyclerViews and my expandableListView`s ArrayList that keeps track of which checkboxes are checked.
After that I put them each into a temporary Arraylist then I add each of those ArrayLists to a single arraylist that will be saved to the file.
private void save(){
//saved_data = new File("saved_data");
/*try {
if(saved_data.exists()==false){
//saved_data.createNewFile();
saved_data.setWritable(true);
}
} catch (IOException e) {
e.printStackTrace();
}*/
File myFile;
try{
myFile = new File(getFilesDir().getAbsolutePath(), "dir/save_data.bin");
myFile.mkdirs();
myFile.createNewFile();
FILENAME = myFile.getName();
}catch (IOException e){
e.printStackTrace();
}
OneFragment f20 = (OneFragment) frags.get(0);
TwoFragment f21 = (TwoFragment) frags.get(1);
ThreeFragment f22 = (ThreeFragment) frags.get(2);
ArrayList saveTasks = f20.adapter.getList();
ArrayList saveReqs = f21.adapter.getList();
ArrayList saveMap = new ArrayList<String>();
if(f22.listAdapter!=null) {
if (f22.listAdapter.getExport() != null) {
saveMap = f22.listAdapter.getExport();
}
}
ArrayList results = new ArrayList();
results.add(saveTasks);
results.add(saveReqs);
results.add(saveMap);
ObjectOutputStream oos1 = null;
FileOutputStream fos1 = null;
try {
fos1 = openFileOutput(FILENAME, Context.MODE_PRIVATE);
oos1 = new ObjectOutputStream(fos1);
oos1.writeObject(results);
oos1.close();
fos1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(oos1 != null){
try {
oos1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In the load code I get the object from the file and update the adapters to their previous state.
private void load(){
//saved_data = new File("saved_data");
ArrayList results = new ArrayList();
FileInputStream fis = null;
ObjectInputStream ois = null;
if(FILENAME==null){
return;
}
try {
fis = new FileInputStream(FILENAME);
ois = new ObjectInputStream(fis);
}catch (FileNotFoundException e) {
e.printStackTrace();
return;
}catch (IOException e) {
e.printStackTrace();
}
try {
while (true) {
results = (ArrayList)(ois.readObject());
}
} catch (OptionalDataException e) {
if (!e.eof) try {
throw e;
} catch (OptionalDataException e1) {
e1.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ois.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
for(int i = 0; i < results.size();i++){
if(i == 0){
frags.set(0,results.get(i));
}
else if(i == 1){
frags.set(1,results.get(i));
}
else if(i == 2){
frags.set(2,results.get(i));
}
else{
}
}
}
When I press the square button at the bottom of the emulator and go back to it one of a few things happen
It crashes saying the file could not be found
W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
And this error points to the load method as the point of failure specifically
FileInputStream fis = null;
When I hit the triangle button nothing happens in logcat, everything is gone upon returning, and the app loses its functions of adding strings to lists on both recyclerViews and displaying both lists in the expandableListView.
Hitting the center circle button and going back to the app is fine nothing breaks.
Since Im getting a file not found error I think that the file isnt getting written
I have searched Stack for a solution and I am new to File IO and fragments, so I have no idea where to go from here.
So i am having trouble with saving my file to the folder. I keep getting
"E/BitmapFactory: Unable to decode stream:
java.io.FileNotFoundException:
/File:/storage/emulated/0/Pictures/Pix/JPG_2016-03-15
02:57:56.264-0400-1837017846.jpg: open failed: ENOENT (No such file or
directory)" error.
I already have WRITE_EXTERNAL_STORAGE permission added so I know it's not that.
Anyways here's my code for the file and the picture callback
public Bitmap createFile() throws IOException {
String mCurrentPhotoPath;
File image;
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "Pix");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.e("Pix", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ").format(new Date());
String imageFileName = "JPG_" + timeStamp;
image = File.createTempFile(imageFileName, ".jpg", mediaStorageDir);
mCurrentPhotoPath = "File:" + image.getAbsoluteFile();
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
Log.d(TAG, "bitmap decoded :(" + bitmap);
return bitmap;
}
public Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap pictureFile = null;
try {
pictureFile = createFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos = new FileOutputStream(String.valueOf(pictureFile));
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found" + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file" + e.getMessage());
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mCamera.startPreview();
}
};
Any help or direction to find the answer is greatly appricated! thanks!
so I'm implementing like music playlist app, my audios are uploaded to Parse.com as mp3 , I want to retrieve those audios ..
final Button btn = (Button) v.findViewById(R.id.button);
final ParseFile fileObject = object.getParseFile("music");
if (fileObject != null) {
fileObject.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, com.parse.ParseException e) {
final String audioFileURL = fileObject.getUrl();
mediaPlayer = new MediaPlayer();
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
try {
mediaPlayer.setDataSource(audioFileURL);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
}//end catch
catch (IOException e1) {
e1.printStackTrace();
}
}//end on click
}//end listener
);
}//end done
});//end get data
}//end if
this is how I retrieve music from Parse.com but this is taking so much time specially that I have a list of audios .. I want a way to download group of the audios in the background .. so when I click the button, the music play so fast .. any help would be greatly appreciated.
I have no time right now to understand why your code doesn't work, but you can take my sample app on github (committed just now), you should solve your problem...if not, let me know. Please, take note of the README.md
https://github.com/fullwipe/ParseAudioFileExample
Hope it helps...
Edit This is the essential part of my repository. Record and save:
String outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/rumor.mp3";
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);
Then, start recording...
try {
myRecorder.prepare();
myRecorder.start();
} catch (IllegalStateException e) {
// start:it is called before prepare()
// prepare: it is called after start() or before setOutputFormat()
e.printStackTrace();
} catch (IOException e) {
// prepare() fails
e.printStackTrace();
}
When you stop recording, save it on Parse.com in this way:
FileInputStream fileInputStream = null;
File fileObj = new File(outputFile);
byte[] data = new byte[(int) fileObj.length()];
try {
//convert file into array of bytes
fileInputStream = new FileInputStream(fileObj);
fileInputStream.read(data);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
ParseFile parseAudioFile = new ParseFile("audiofile.mp3", data);
parseAudioFile.saveInBackground();
ParseObject parseObject = new ParseObject("AudioFileClass");
parseObject.put("audiofile", parseAudioFile);
parseObject.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplicationContext(),"Audio file saved successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),"Error: audio file not saved", Toast.LENGTH_SHORT).show();
}
}
});
Retrieve and play from Parse.com is very simple, I have used a ParseQueryAdapter. This is the part where you get the mp3 file and play it:
ParseFile descr = object.getParseFile("audiofile");
if (descr != null) {
String audioFileURL = descr.getUrl();
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(audioFileURL);
mediaPlayer.prepare();
mediaPlayer.start();
}
...
...
I want to change the background color for layouts dynamically for the first time only, using configuration file in android that file should be in assets folder,it can be xml file or anything.
please help me.
If you set an ID to your layout as follows :
<LinearLayout android:id="#+id/myLayout">
<LinearLayout/>
Then you can set your backGround in onCreate like this:
myLayout= findViewById(R.id.myLayout);
myLayout.setBackgroundColor(Color.BLUE);
1.use color for int value.
in the assets file config.txt, you can input color for int value like this. for example this value is Color.RED
4294901760
2.use this code in your appliaction
String config = "config.txt";
InputStream is = null;
try {
is = getAssets().open(config);
DataInputStream dis = new DataInputStream(is);
String color = dis.readUTF();
ColorDrawable drawable = new ColorDrawable(Integer.parseInt(color));
//use drawable
//for example
new TextView(this).setBackgroundColor(Integer.parseInt(color));
new TextView(this).setBackgroundDrawable(drawable);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(is != null)
{
try {
is.close();
} catch (IOException e) {
}
}
}
3.you can use reflect, but in the config file, write the color name from values/colors.xml.
String config = "config.txt";
InputStream is = null;
try {
is = getAssets().open(config);
DataInputStream dis = new DataInputStream(is);
String color = dis.readUTF();
try {
Field field = R.color.class.getDeclaredField(color);
field.setAccessible(true);
Integer id = (Integer) field.get(null);
ColorDrawable drawable = new ColorDrawable(getResources().getColor(id));
// use drawable
// for example
new TextView(this).setBackgroundColor(getResources().getColor(id));
new TextView(this).setBackgroundDrawable(drawable);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
}