I am really facing problem from last couple of days but I am not able to find the exact solution please help me.
I want to merge two .mp3 or any audio file and play final single one mp3 file. But when I am combine two file the final file size is ok but when I am trying to play it just play first file, I have tried this with SequenceInputStream or byte array but I am not able to get exact result please help me.
My code is the following:
public class MerginFileHere extends Activity {
public ArrayList<String> audNames;
byte fileContent[];
byte fileContent1[];
FileInputStream ins,ins1;
FileOutputStream fos = null;
String combined_file_stored_path = Environment
.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/final.mp3";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audNames = new ArrayList<String>();
String file1 = Environment.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/one.mp3";
String file2 = Environment.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/two.mp3";
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/AudioRecorder/" + "final.mp3");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
audNames.add(file1);
audNames.add(file2);
Button btn = (Button) findViewById(R.id.clickme);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
createCombineRecFile();
}
});
}
public void createCombineRecFile() {
// String combined_file_stored_path = // File path in String to store
// recorded audio
try {
fos = new FileOutputStream(combined_file_stored_path, true);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
File f = new File(audNames.get(0));
File f1 = new File(audNames.get(1));
Log.i("Record Message", "File Length=========>>>" + f.length()+"------------->"+f1.length());
fileContent = new byte[(int) f.length()];
ins = new FileInputStream(audNames.get(0));
int r = ins.read(fileContent);// Reads the file content as byte
fileContent1 = new byte[(int) f1.length()];
ins1 = new FileInputStream(audNames.get(1));
int r1 = ins1.read(fileContent1);// Reads the file content as byte
// from the list.
Log.i("Record Message", "Number Of Bytes Readed=====>>>" + r);
//fos.write(fileContent1);// Write the byte into the combine file.
byte[] combined = new byte[fileContent.length + fileContent1.length];
for (int i = 0; i < combined.length; ++i)
{
combined[i] = i < fileContent.length ? fileContent[i] : fileContent1[i - fileContent.length];
}
fos.write(combined);
//fos.write(fileContent1);*
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
Log.v("Record Message", "===== Combine File Closed =====");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I already published an app with this function... try my method using SequenceInputStream, in my app I just merge 17 MP3 files in one and play it using the JNI Library MPG123, but I tested the file using MediaPlayer without problems.
This code isn't the best, but it works...
private void mergeSongs(File mergedFile,File...mp3Files){
FileInputStream fisToFinal = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mergedFile);
fisToFinal = new FileInputStream(mergedFile);
for(File mp3File:mp3Files){
if(!mp3File.exists())
continue;
FileInputStream fisSong = new FileInputStream(mp3File);
SequenceInputStream sis = new SequenceInputStream(fisToFinal, fisSong);
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fisSong.read(buf)) != -1;)
fos.write(buf, 0, readNum);
} finally {
if(fisSong!=null){
fisSong.close();
}
if(sis!=null){
sis.close();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fos!=null){
fos.flush();
fos.close();
}
if(fisToFinal!=null){
fisToFinal.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Mp3 files are some frames.
You can concatenate these files by appending the streams to each other if and only if the bit rate and sample rate of your files are same.
If not, the first file plays because it has truly true encoding but the second file can not decode to an true mp3 file.
Suggestion: convert your files with some specific bit rate and sample rate, then use your function.
Related
I need when app starts, to check if file exists, if not to be created..
I need a block of code to append files into it
than I need a block of code that read that text line by line
than to remove a line ....
I found this code at stackoverflow, and they said that the file will be created in that location...
//Here I have this :
//Do not hardcode "/data/"; use Context.getFilesDir().getPath() instead
//
String filePath = "/data/data/com.example.myapp/files/text.txt";
File file = new File(filePath);
if(file.exists()){
//Do nothing
}
else{
try {
final String TESTSTRING = new String("");
FileOutputStream fOut = openFileOutput("text.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(TESTSTRING);
osw.flush();
osw.close();
} catch (IOException ioe)
{ioe.printStackTrace();}
}
}
To add Lines in text I made this :
private void write(){
S ="/data/data/com.example.myapp/files/text.txt";
try {
writer = new FileWriter(S, true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
writer.write(emri.getText().toString() + "\n" + link.getText().toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And when I have to read them :
public class PlayList extends ListActivity {
ArrayList<String> listaE = new ArrayList<String>();
ArrayList<String> listaL = new ArrayList<String>();
InputStream instream;
int resh=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lexo();
String[] mStringArray = new String[listaE.size()];
mStringArray = listaE.toArray(mStringArray);
setListAdapter(new ArrayAdapter<String>(PlayList.this,android.R.layout.simple_list_item_1,mStringArray));
}
private void lexo(){
String S ="/data/data/com.example.myapp/files/text.txt";
try {
// open the file for reading
instream = new FileInputStream(S);
// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
do {
line = buffreader.readLine();
if ((resh % 2) == 0) {
listaL.add(line);
}
else {
listaE.add(line);
}
// do something with the line
} while (line != null);
}
} catch (Exception ex) {
// print stack trace.
} finally {
// close the file.
try {
instream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My code does not work at all, and is missing the code to remove a line..
So everything I need is :
Code to write into file ( file to be saved because will be used until the app will be installed )
Code to read that file line by line ( so to be added in array, odd lines in one array, other lines in another array )
Code to remove a line from that file ( array to be added in listview and when user touches the line, touched line to be removed )
To add lines on list-activity
Any help will be very very appreciated,
Thanks...
First of all, you should use .getFilesDir().getPath() on your app's context, instead of hardcoding the path. That's commented in your first block. Second, create an OutputStream like this:
OutputStream out = new FileOutputStream(filePath);
If you have an InputStream called in, you'll be able to write it to a file using this code:
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
in.close();
out.close();
When you do create a file, check the rest (I didn't look) and get back to StackOverlow, if it fails. Don't make any of us do all the work, okay? Rip it to small part and make an effort.
Good luck with your work.
earlier i transfer only video file over socket but when i require file size on the other end then problem occured,so i thought to send Object through Socket but there comes problem with file size limit.It transfer files upto size of 45MB however i want to transfer files of size more than that.
i have posted code below:
public class WiFiDirectBundle implements Serializable {
private String fileName;
private String fileType;
private Long fileSize;
ArrayList<byte[]> chunks;
ArrayList<Integer> a;
static int len=0;
byte[] buf;
public WiFiDirectBundle() {
// TODO Auto-generated constructor stub
}
public void setFile(String path) throws FileNotFoundException,
IOException {
File f = new File(path);
fileName = f.getName();
fileType = MimeTypeMap.getFileExtensionFromUrl(f.getAbsolutePath());
fileSize = f.length();
Log.d(WiFiDirectActivity.TAG,"name of file is"+fileName);
Log.d(WiFiDirectActivity.TAG,"size of file is"+fileSize);
FileInputStream fin = null;
try {
fin = new FileInputStream(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileContent = new byte[(int) f.length()];
try {
fin.read(fileContent);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fin.close();
}
// restores the file of the bundle, given its directory (change to whatever
// fits you better)
public String restoreFile(String baseDir) throws IOException {
File f = new File(baseDir + "/" + fileName);
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
try {
FileOutputStream fos = new FileOutputStream(f);
if (fileContent != null) {
fos.write(fileContent);
}
fos.close();
return f.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
I think this fileContent = new byte[(int) f.length()]; in your code might cause Out of memory. As you have declared byte[] buf;, why not use a buf instead?
There is Arabic encoded pdf file that is received from a server via a web service in my Android application, then I decode it and save it to be cashed to open it anytime,this is the file I download_which also is encoded_ the problem is the file became not searchable anymore, this is the code I use to decode the file:
protected Void doInBackground(String... myLink) {
if (conDetector.isConnectingToInternet()) {
File myDir = getFilesDir();
String fileName = PDFCACHE;
File cachedFile = new File(myDir, fileName);
// to check if the cached file in the memory or not
if (cachedFile.exists()) {
try {
readPDFFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (!cachedFile.exists()) {
try {
URL url = new URL(myLink[0]);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
file_size = urlConnection.getContentLength();
source = new BufferedInputStream(url.openStream(), 8192);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
buffer = new byte[1024];
long total = 0;
int count = 0;
// buffer=new
// Scanner(source).useDelimiter("\\A").next().getBytes();*/
// buffer = Base64.decode(buffer, 0);
for (int i; (i = source.read(buffer)) != -1;) {
total += i;
bos.write(buffer, 0, i); // no doubt here is 0
publishProgress(""
+ (int) ((total * 100) / file_size));
}
if (flag == false) {
bytes = bos.toByteArray();
bytes = Base64.decode(bytes, Base64.DEFAULT);
String decodedString = new String(bytes);
if (bytes != null) {
openBuffer(bytes);
if (manipulateCache())
try {
savePDFFile(bytes);
// source.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
core = openFile(decodedString);
}
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// when there is no internet connection "offline mode"
} else if (!(conDetector.isConnectingToInternet())) {
if (!PDFCACHE.equals(null)) {
try {
readPDFFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
} }
The file you received is not searchable, the font objects contain ToUnicode maps claiming most of the glyphs used are numbers, symbols, or Latin characters which does not match their appearance as Arabic characters.
Thus, no standard PDF viewer can be used to search the files.
I used the following code to move the audio file form res/raw folder to SD card, when i execute this code, the file won't move. why it will happens, in which line i made mistake.
MoveAudio.java
public class MoveAudioextends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button a = (Button) findViewById(R.id.Button01);
a.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
byte[] buffer = null;
InputStream fIn = getBaseContext().getResources()
.openRawResource(R.raw.song);
int size = 0;
System.out.println("<<<<<<<SIZE>>>>>>>>>>>>>>>>>>>>" + fIn);
try {
size = fIn.available();
System.out
.println("<<<<<<<SIZE>>>>>>>>>>>>>>>>>>>>" + size);
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
String path = "/sdcard/media/audio/ringtones/";
String filename = "examplefile" + ".ogg";
boolean exists = (new File(path)).exists();
if (!exists) {
System.out
.println("<<<<<<<FALSE SO INSIDE THE CONDITION>>>>>>>>>>>>>>>>>>>>");
new File(path).mkdirs();
}
FileOutputStream save;
try {
save = new FileOutputStream(path + filename);
System.out
.println("<<<<<<<SAVE>>>>>>>>>>>>>>>>>>>>" + save);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.parse("file://" + path + filename)));
File k = new File(path, filename);
System.out.println("<<<<<<<SAVE>>>>>>>>>>>>>>>>>>>>" + k);
}
});
}
}
In my xml file i had sing button, when i click that button the file will move. This code executes without error but the file won't move.
Instead of having empty catch blocks, try instead to write those out.
e.printStackTrace();
// I believe it is.
Additionally, have you permissions to write to the SD Card?
permission.WRITE_EXTERNAL_STORAGE
What is the filename of the song in your resource folder? The reason i ask is that there is a max file size that can be read back for a file that is compressed. Your file, if named with a .ogg extension shouldn't be compressed and thus not constrained to this limit. However if you named it something else that gets compressed it may have this problem.
A good way to log errors is to use androids Log methods. Do so like this:
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.e(TAG, "FileNotFoundException", e);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "IOException", e);
}
You may be getting a "Data exceeds UNCOMPRESS_DATA_MAX (1290892 vs 1048576)" message.
The only way to tell for sure though is to log your error. It is also possible the SD card is out of space or you don't have permissions to write to it.
In this example, my raw file is "test.pdf"
We will use "Download" folder in our phone.
"test.pdf" in raw folder will be moved to "Download/test_filemove" folder as "example.pdf"
Make the new "raw" folder in "res" folder.
Copy "test.pdf" to "raw" folder.
Surely you should make Button01 in your layout.
Don't forget to give permission in your manifest file as below
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
I just modify your example a little bit.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button a = (Button) findViewById(R.id.Button01);
a.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
byte[] buffer = null;
InputStream fIn = getBaseContext().getResources()
.openRawResource(R.raw.test);
int size = 0;
System.out.println("<<<<<<<SIZE>>>>>>>>>>>>>>>>>>>>" + fIn);
try {
size = fIn.available();
System.out
.println("<<<<<<<SIZE>>>>>>>>>>>>>>>>>>>>" + size);
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/test_filemove/";
String filename = "example" + ".pdf";
boolean exists = (new File(path)).exists();
if (!exists) {
System.out
.println("<<<<<<<FALSE SO INSIDE THE CONDITION>>>>>>>>>>>>>>>>>>>>");
new File(path).mkdirs();
}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
System.out
.println("<<<<<<<SAVE>>>>>>>>>>>>>>>>>>>>" + save);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
I hope this help you out.
I am having approx 300-400 images with the size of 320x480 pixels in jpg format. I have to add this images on the SD Card. Currently I am putting this images in the Drawable folder in my project. Now I want to move this images on sd card and through that i wish to use this images for animation purpose. I also want to check that SD Card is mounted or not when my application starts first. I am not having any idea of programming of SD CARD in android so please anyone is having any idea or links for beginner kindly let me know.
CODE
ImageView imgAssets;
String path="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
path = Environment.getExternalStorageDirectory().toString();
try {
copyFromAsstesToSDCard();
readFromSDCard();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void readFromSDCard() {
// TODO Auto-generated method stub
File dir = Environment.getExternalStorageDirectory();
//File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
//Get the text file
File file = new File(dir.getAbsolutePath()+ "/cat_angry10.jpg");
// i have kept text.txt in the sd-card
//System.out.println(file.toString());
if(file.exists()) // check if file exist
{
try {
Bitmap bitMap = BitmapFactory.decodeFile(Environment.getExternalStorageState() + "/cat_angry10.jpg");
//imgAssets.setImageBitmap(bitMap);
imgAssets.setBackgroundDrawable(new BitmapDrawable(bitMap));
}
catch (Exception e) {
//You'll need to add proper error handling here
e.printStackTrace();
}
}
else
{
System.out.println("Sorry file doesn't exist!!");
}
}
public void copyFromAsstesToSDCard() {
// TODO Auto-generated method stub
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("Images");
} catch (IOException e) {
Log.e("tag", e.getMessage());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
for(String filename : files) {
System.out.println("File name => "+filename);
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("Images/"+filename); // if files resides inside the "Files" directory itself
out = new FileOutputStream(Environment.getExternalStorageDirectory().toString() + "/" + filename);
System.out.println(out.toString());
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
}
private void copyFile(InputStream in, OutputStream out) {
// TODO Auto-generated method stub
byte[] buffer = new byte[1024];
int read;
try {
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am getting NullPointerException when reading image from SD CARD.
Thanks
Keyur
Here are some links - if you have a problem using these, post your code and I'll try to help further.
Android write to sd card folder
http://androidgps.blogspot.com/2008/09/writing-to-sd-card-in-android.html
https://sites.google.com/site/androidhowto/how-to-1/save-file-to-sd-card