Merge two mp3 file in android - android

I want merge multiple mp3 file in android but for example I just do this with two file :
FileInputStream fileInputStream = new FileInputStream(soundFile.getAbsolutePath() + 0);
FileInputStream fileInputStream1 = new FileInputStream(soundFile.getAbsolutePath() + 1);
SequenceInputStream sequenceInputStream = new SequenceInputStream(fileInputStream, fileInputStream1);
FileOutputStream fileOutputStream = new FileOutputStream(soundFile.getAbsolutePath());
int temp;
while ((temp = sequenceInputStream.read()) != -1) {
fileOutputStream.write(temp);
}
fileInputStream.close();
fileInputStream1.close();
sequenceInputStream.close();
fileOutputStream.close();
I recorded two sound with "ttt.mp30" and "ttt.mp31" file. then I want to merge it to "ttt.mp3"
but when I use this code for merge, it just create the ttt.mp3 witch play ttt.mp30 but it doesn't play ttt.mp31 file
whats the problem ?
thanks
EDIT :
if I use :
SequenceInputStream sequenceInputStream = new SequenceInputStream(fileInputStream1, fileInputStream);
insted of :
SequenceInputStream sequenceInputStream = new SequenceInputStream(fileInputStream, fileInputStream1);
the ttt.mp3 just play ttt.mp31 file
Edit :
the record option :
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);

import java.io.*;
public class TwoFiles
{
public static void main(String args[]) throws IOException
{
FileInputStream fistream1 = new FileInputStream("path\\1.mp3"); // first source file
FileInputStream fistream2 = new FileInputStream("path\\2.mp3");//second source file
SequenceInputStream sistream = new SequenceInputStream(fistream1, fistream2);
FileOutputStream fostream = new FileOutputStream("path\\final.mp3");//destinationfile
int temp;
while( ( temp = sistream.read() ) != -1)
{
// System.out.print( (char) temp ); // to print at DOS prompt
fostream.write(temp); // to write to file
}
fostream.close();
sistream.close();
fistream1.close();
fistream2.close();
}
}

Related

Cannot get the real file path - Android Oreo 8+

I'm downloading a file using Download Manager and saving into Download Folder.
After download finish i'm picking up the folder path like this way:
int uriIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
String downloadedPackageUriString = cursor.getString(uriIndex);
Then i need to use this path to unzip the file downloaded. The code to unzip it is below:
SouceFile is the path from downloadmanager.
unzip(String sourceFile, String destinationFolder)
try {
zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(sourceFile)));
ZipEntry ze;
int count;
byte[] buffer = new byte[BUFFER_SIZE];
while ((ze = zis.getNextEntry()) != null) {
String fileName = ze.getName();
fileName = fileName.substring(fileName.indexOf("/") + 1);
File file = new File(destinationFolder, fileName);
File dir = ze.isDirectory() ? file : file.getParentFile();
Log.i("MainService", "Unzipping fileName: " + fileName);
file_path = destinationFolder + "/" + fileName;
if (!dir.isDirectory() && !dir.mkdirs())
throw new FileNotFoundException("Invalid path: " + dir.getAbsolutePath());
if (ze.isDirectory()) continue;
FileOutputStream fout = new FileOutputStream(file);
try {
while ((count = zis.read(buffer)) != -1) {
fout.write(buffer, 0, count);
}
} finally {
fout.close();
}
list_filenames.add(file_downloaded);
}
Log.d("MainService", "TAM:" + tam);
} catch (IOException ioe) {
Log.d("MainService", "Oiiiiiiiiii " + ioe);
return list_filenames;
} finally {
if (zis != null)
try {
zis.close();
} catch (IOException e) {
}
}
The code to unzip works on Android 6 (My phone), but on Android Oreo + it doesnt.
I'm getting (No such file or directory) from zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(sourceFile)));
Reinforcing: I'm not getting this error on Android 6. Just on 8+
Thanks for any help.
I tried some suggestions from other guys here with similar problem, but doesnt works for me.
I'm not getting this error on Android 6
At most, you are not getting this error on the one device that you tested on Android 6.0. There are many device models running Android 6.0, not just one.
COLUMN_LOCAL_URI is supposed to give you a string representation of a Uri. That will not work with FileInputStream, because a Uri is not a file.
Replace:
zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(sourceFile)));
with:
zis = new ZipInputStream(new BufferedInputStream(cr.openInputStream(Uri.parse(sourceFile))));
...where cr is a ContentResolver that you get by calling getContentResolver() on some Context.

merging recorded audio with existing mp3 file android

I am learning android development, and trying to make face filters with sound in background like snapchat or Facebook. But I am unable to record the audio playing in the filter with user sound while using headphones.
Please help! or some links which can be useful for me
import java.io.*;
public class TwoFiles
{
public static void main(String args[]) throws IOException
{
FileInputStream fistream1 = new FileInputStream("C:\\Temp\\1.mp3"); // first source file
FileInputStream fistream2 = new FileInputStream("C:\\Temp\\2.mp3");//second source file
SequenceInputStream sistream = new SequenceInputStream(fistream1, fistream2);
FileOutputStream fostream = new FileOutputStream("C:\\Temp\\final.mp3");//destinationfile
int temp;
while( ( temp = sistream.read() ) != -1)
{
// System.out.print( (char) temp ); // to print at DOS prompt
fostream.write(temp); // to write to file
}
fostream.close();
sistream.close();
fistream1.close();
fistream2.close();
}
}

append text to the end of the file

I am using the below code segment to write text to the end o the file for each time it is called. But, it is erasing the old data and then writes the new data to the beginning of the file. How can I fix the below code so that it is append new data always end of the file ?
public boolean writeToFile(String directory, String filename, String data ){
File out;
OutputStreamWriter outStreamWriter = null;
FileOutputStream outStream = null;
out = new File(new File(directory), filename);
if ( out.exists() == false ){
out.createNewFile();
}
outStream = new FileOutputStream(out) ;
outStreamWriter = new OutputStreamWriter(outStream);
outStreamWriter.append(data);
outStreamWriter.flush();
}
Try to set append boolean value to true in FileOutputStream:
outStream = new FileOutputStream(out, true);
outStreamWriter = new OutputStreamWriter(outStream);

How to compress a folder to make docx file in android?

I'm trying to make an Android application that can open a docx file to read, edit and save it.
My idea is to extract all the xml file within the archive to a temp folder. In this folder we can edit the content of the docx in /word/document.xml. The problem is when I compress this temp folder to make a new docx file and replace the old file, inside the new docx archive the path is like /mnt/sdcard/temp/"all files xml go here" while the xml files should be in the first level.
Can anybody help me to go through this? here is the method to compress the temp directory
Note: dir2zip argument's value I use is /mnt/sdcard/temp/***.docx
public void zipDir(String dir2zip, ZipOutputStream zos)
{
try
{
//create a new File object based on the directory we
//have to zip File
File zipDir = new File(dir2zip);
//get a listing of the directory content
String[] dirList = zipDir.list();
byte[] readBuffer = new byte[2156];
int bytesIn = 0;
//loop through dirList, and zip the files
for(int i=0; i<dirList.length; i++)
{
File f = new File(zipDir, dirList[i]);
if(f.isDirectory())
{
//if the File object is a directory, call this
//function again to add its content recursively
String filePath = f.getPath();
zipDir(filePath, zos);
//loop again
continue;
}
//if we reached here, the File object f was not a directory
//create a FileInputStream on top of f
FileInputStream fis = new FileInputStream(f);
//create a new zip entry
ZipEntry anEntry = new ZipEntry(f.getPath());
//place the zip entry in the ZipOutputStream object
zos.putNextEntry(anEntry);
//now write the content of the file to the ZipOutputStream
while((bytesIn = fis.read(readBuffer)) != -1)
{
zos.write(readBuffer, 0, bytesIn);
}
//close the Stream
fis.close();
}
}
catch(Exception e)
{
//handle exception
}
}
I have managed to fix it by myself. The problem is in this line:
File f = new File(zipDir, dirList[i]);
It should be
File f = new File(dirList[i]);
If the argument zipDir is included, the absolute path to the directory will be used in the archive!
I have now managed to get the original poster's code working on Mac and Windows by making the following two modifications:
1: add a ZipEntry for each directory: do not simply ignore it
2: remove the directory name from the ZipEntry name
Note: zipinfo is useful
This is a program that works for me:
import java.io.*;
import java.util.zip.*;
public class zipdoc
{
String savedDir = null;
public void zipDir(String dir2zip, ZipOutputStream zos)
{
try
{
if (savedDir == null)
savedDir = dir2zip;
// create a new File object based on the directory we
// have to zip File
File zipDir = new File(dir2zip);
//get a listing of the directory content
String[] dirList = zipDir.list();
byte[] readBuffer = new byte[2156];
int bytesIn = 0;
// loop through dirList, and zip the files
for (int i=0; i<dirList.length; i++)
{
File f = new File(zipDir, dirList[i]);
if (f.isDirectory())
{
// if the File object is a directory, call this
// function again to add its content recursively
System.out.println("Adding dir: " + f);
// create a new zip entry
ZipEntry anEntry = new ZipEntry(f.getPath().substring(savedDir.length()+1) + "/");
// place the zip entry in the ZipOutputStream object
zos.putNextEntry(anEntry);
String filePath = f.getPath();
zipDir(filePath, zos);
// loop again
continue;
}
else if (!f.getName().equals(".DS_Store"))
{
// if we reached here, the File object f was not a directory
// and it's not the MacOSX special .DS_Store
// create a FileInputStream on top of f
System.out.println("Adding file: " + f);
FileInputStream fis = new FileInputStream(f);
// create a new zip entry
ZipEntry anEntry = new ZipEntry(f.getPath().substring(savedDir.length()+1));
// place the zip entry in the ZipOutputStream object
zos.putNextEntry(anEntry);
// now write the content of the file to the ZipOutputStream
while((bytesIn = fis.read(readBuffer)) != -1)
{
zos.write(readBuffer, 0, bytesIn);
}
// close the Stream
fis.close();
}
}
}
catch(Exception e)
{
// handle exception
System.out.println(e);
}
}
public void zipit(String inDir, String outFile)
{
try {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(outFile)));
zos.setMethod(0);
zos.setMethod(ZipOutputStream.DEFLATED);
zos.setLevel(0);
zipDir(inDir, zos);
zos.finish();
zos.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
public static void main (String args[]) {
zipdoc z1 = new zipdoc();
// Check there are sufficient params if desired
// first param is directory to be 'zipped', second is resulting
// filename (??.docx)
// eg java zipdoc dir1 newDoc.docx
z1.zipit(args[0], args[1]);
System.out.println("Finished creating " + args[1]);
}
}

Android: Unzipping files throws data errors or CRC errors

I'm working on a project that downloads a zip file and unzips locally. The issue I'm hitting is that the unzip process works like 5% of the time.
It's a mystery to me at this point because sometimes it works, but most of the time it throws data or crc errors. It'll even switch between erros even though the zip file hasn't changed.
I've tried zip files that were created by numerous tools wondering if the format was incorrect. But to no avail. Even zips created in the terminal don't work.
Here's my unzipping code:
try {
String _location = model.getLocalPath();
FileInputStream fin = new FileInputStream(localFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
byte[] buffer = new byte[1024];
while((ze = zin.getNextEntry()) != null) {
if(_cancel) break;
System.out.println("unzipping " + ze.getName());
if(ze.isDirectory()) {
File f = new File(_location + ze.getName());
f.mkdirs();
} else {
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
for(int c = zin.read(buffer); c > 0; c = zin.read(buffer)) {
fout.write(buffer,0,c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
if(_cancel) {
handler.post(dispatchCancel);
return;
}
} catch(Exception e) {
System.out.println("UNZIP ERROR!");
System.out.println(e.getMessage());
System.out.println(e.toString());
e.printStackTrace();
}
And here's how I typically create the zip file.
$>zip -r myzip.zip myzip/
Here are the two error outputs:
java.util.zip.ZipException: CRC mismatch
at java.util.zip.ZipInputStream.readAndVerifyDataDescriptor(ZipInputStream.java:209)
at java.util.zip.ZipInputStream.closeEntry(ZipInputStream.java:173)
at com.XX.XX.XXIssueDownloader$7.run(XXIssueDownloader.java:222)
at java.lang.Thread.run(Thread.java:1020)
java.util.zip.ZipException: data error
at java.util.zip.ZipInputStream.read(ZipInputStream.java:336)
at java.io.FilterInputStream.read(FilterInputStream.java:133)
at com.XX.XX.XXIssueDownloader$7.run(XXIssueDownloader.java:219)
at java.lang.Thread.run(Thread.java:1020)
Anyone have any idea why I might get these errors? I'm not getting anywhere with these.
There are two things very important when loading Zip files.
Make sure you're using a request method that doesn't contain the Accept-Encoding: header. If it's in the request then the response is not a zip file, it's a gzip compressed zip file. So if you're writing that directly to disk while it's downloading then it won't actually be a zip file. You can use something like this to load the zip file:
URL url = new URL(remoteFilePath);
URLConnection connection = url.openConnection();
InputStream in = new BufferedInputStream(connection.getInputStream());
FileOutputStream f = new FileOutputStream(localFile);
//setup buffers and loop through data
byte[] buffer = new byte[1024];
long total = 0;
long fileLength = connection.getContentLength();
int len1 = 0;
while((len1 = in.read(buffer)) != -1) {
if(_cancel) break;
total += len1;
_Progress = (int) (total * 100 / fileLength);
f.write(buffer,0,len1);
handler.post(updateProgress);
}
f.close();
in.close();
When using input and out streams, do NOT use the read(buffer) or write(buffer) method, you need to use read/write(buffer,0,len). Otherwise what you're writing or reading may end up with garbage data in it. The former (read(buffer)) will always read the entire buffer, but there may actually not be a full buffer, for example if the last iteration of the loop only read 512 bytes. So here's how you'd unzip the file:
String _location = model.getLocalPath();
FileInputStream fin = new FileInputStream(localFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while((ze = zin.getNextEntry()) != null) {
if(_cancel) break;
System.out.println("unzipping " + ze.getName());
System.out.println("to: " + _location + ze.getName());
if(ze.isDirectory()) {
File f = new File(_location + ze.getName());
f.mkdirs();
} else {
byte[] buffer2 = new byte[1024];
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
for(int c = zin.read(buffer2); c > 0; c = zin.read(buffer2)) {
fout.write(buffer2,0,c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();

Categories

Resources