What I am doing: I am currently recording voice and saving it as a file in SDCard which is running / playing fine in MediaPlayer.
What I want: When I encode this file intoBase64 and send to server, everything goes fine. But When i decode the Base64 String into audio.m4a file, it is not running in MediaPlayer.
I had tried .m4a , .wav but all in vain.
The problem is in encoding. Because when I decode a file sent from the same iOS app, it runs fine in MediaPlayer.
I know its very basic and alot of help is there to encode decode but nothing is working. Following is my approach:
private void encodeAudio(String selectedPath) {
byte[] audioBytes;
try {
// Just to check file size.. Its is correct i-e; Not Zero
File audioFile = new File(selectedPath);
long fileSize = audioFile.length();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(new File(selectedPath));
byte[] buf = new byte[1024];
int n;
while (-1 != (n = fis.read(buf)))
baos.write(buf, 0, n);
audioBytes = baos.toByteArray();
// Here goes the Base64 string
_audioBase64 = Base64.encodeToString(audioBytes, Base64.DEFAULT);
} catch (Exception e) {
DiagnosticHelper.writeException(e);
}
}
And Decoding in the following way:
private void decodeAudio(String base64AudioData, File fileName, String path, MediaPlayer mp) {
try {
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(Base64.decode(base64AudioData.getBytes(), Base64.DEFAULT));
fos.close();
try {
mp = new MediaPlayer();
mp.setDataSource(path);
mp.prepare();
mp.start();
} catch (Exception e) {
DiagnosticHelper.writeException(e);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Please point if I am doing anything wrong/silly.
try to use Multipartentity to upload any type of file to server.
public void postFile(String file_path, String url){
File file = new File(file_path);
try {
System.out.println(file_path);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", bin); /*I believe that the "file" is the name in php part*/
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.i("RESPONSE", EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
}
Related
I am new dev for Android studio.I want a create music player.But,this music player online songs download then will play ve and read song from storage. I'm a little inexperienced at this. I don't know how to download songs from internet with code to my project. Which method, code, library or API should I use? I want to use kotlin language. Who can help me with this issue
This code works:
private static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return;
} catch (IOException e) {
return;
}
}
Make sure you have Manifest.permissions.READ_EXTERNAL_STORAGE declared in your Manifest.
Then
File files = new File(Environment.getExternalStorageDirectory().toString());
String file = downloadFile("yourweb.com/music.mp3", files);
String directory = Environment.getExternalStorageDirectory()+"/music.mp3";
MediaPlayer mediaPlayer = MediaPlayer.create(MainActivity.this, directory);
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
Result is not guaranteed. You can try it
I am developing app like playstore in which user can download any app. i have many apps in my application that i got from my website through wp api v2. when we click on any of the available application detail opened and it have a download link. when we click on the link it goes to the browser but what i want is when we click on any of the apps downloading link downloading should start within my app with progress bar. i didn't found any appropriate solution yet on stack or anywhere.
Here is the screenshot attached for better understanding. arrow is pointing to the downloading link.
Try this code, you can put this on click of the link(textview)
private static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return; // swallow a 404
} catch (IOException e) {
return; // swallow a 404
}
}
you can use intent service to download the app.
Here is the code :
public class DownloadService extends IntentService {
File cacheDir;
public DownloadService() {
super("DownloadService");
}
#Override
public void onCreate() {
super.onCreate();
String tmpLocation =
Environment.getExternalStorageDirectory().getPath();
cacheDir = new File(tmpLocation);
if (!cacheDir.exists()) {
cacheDir.mkdirs();
}
}
#Override
protected void onHandleIntent(Intent intent) {
String remoteUrl = intent.getExtras().getString("url");
String location;
String filename =
remoteUrl.substring(
remoteUrl.lastIndexOf(File.separator) + 1);
File tmp = new File(cacheDir.getPath()
+ File.separator + filename);
if (tmp.exists()) {
location = tmp.getAbsolutePath();
stopSelf();
return;
}
try {
URL url = new URL(remoteUrl);
HttpURLConnection httpCon =
(HttpURLConnection) url.openConnection();
if (httpCon.getResponseCode() != 200)
throw new Exception("Failed to connect");
InputStream is = httpCon.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1 != (n = is.read(buf))) {
out.write(buf, 0, n);
}
out.close();
is.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(tmp);
fos.write(response);
fos.flush();
fos.close();
is.close();
location = tmp.getAbsolutePath();
} catch (Exception e) {
Log.e("Service", "Failed!", e);
}
}
}
Run this service with url passed in the intent
We have an Android app, which we deploy by opening a browser on the device go to the customer url, then the browser downloads the file. We are also trying to download a separate .xml settings file. If I try this with in the browser, the xml will just display. In the Android app, could I copy the xml from the cache?
Is there any other way of downloading the xml?
Could I use a different file type, which the browser would download?
Thanks
Here's a method to download an xml file from a URL
try {
//set the download URL, a url that points to a file
URL url = new URL("http://your/path/to/file.xml");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
//set the path where we want to save the file
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,"data.xml");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
progressDialog.setMax(totalSize);
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You should probably do this in the background, i.e. use an AsyncTasc.
If you need to load a small xml file the Document class is fairly straight forward to use. You can use an http get request to grab the xml file. Here is a simple function you can call, pass in a url, and get a xml document object you can dig into:
public static Document getXML(final String url) throws ExecutionException, InterruptedException {
Document out = null;
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Document> result = executor.submit(new Callable<Document>() {
public Document call() throws Exception {
HttpGet uri = new HttpGet(url);
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse resp = null;
try {
resp = client.execute(uri);
} catch (IOException e) {
e.printStackTrace();
}
StatusLine status = resp.getStatusLine();
if (status.getStatusCode() != 200) {
Log.d("http error", "HTTP error, invalid server status code: " + resp.getStatusLine());
}
// try {
HttpEntity entity = resp.getEntity();
InputStream in = entity.getContent();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Document dom = null;
try {
dom = builder.parse(in);
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return dom;
}
});
try {
out = result.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return out;
}
I want to download and play video files during downloading. Since VideoView is not helping with this matter I decided to work with nanoHTTPd to create a pseudo HTTP server and inside my own server try to download video file and play it afterward but my problem is :
1-How can I flush downloaded part to videoview and download the remaining parts?
Following is my source :
public class VideoStreamingServer extends NanoHTTPD {
public VideoStreamingServer() {
// by default listening on port 8080
super(8080);
}
#Override
public Response serve(String URI, Method method,
Map header, Map parameters, Map files) {
FileInputStream fis = null;
try {
// fis = new FileInputStream("/mnt/sdcard/p/1.mp4");
File bufferFile = File.createTempFile("test", "mp4");
BufferedOutputStream bufferOS = new BufferedOutputStream(
new FileOutputStream(bufferFile));
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.example.net/dl/1.mp4");
HttpResponse response = client.execute(request);
Header[] headers = response.getAllHeaders();
Log.e("Internet buffer", "connected to server");
BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent(), 2048);
byte[] buffer = new byte[16384];
int numRead;
boolean started = false;
while ((numRead = bis.read(buffer)) != -1) {
bufferOS.write(buffer, 0, numRead);
bufferOS.flush();
totalRead += numRead;
if (totalRead > 120000 && !started) {
//problem starts here
//How can I flush the buffer to VideoView?
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new NanoHTTPD.Response(Response.Status.OK, "video/mp4", fis);
}
}
Found a way, you can read more about it here : http://www.vahidhashemi.com/?p=120
How would i know if i downloading of images failed?
What happens is that i download the image url first, and from there get the image filename to store to my database. Then have two methods to download from the url, and save is as the filename. Btw, they are being called by a method that is being called by an AsyncTask.
Here are the two methods (that are handed down by my senior) that is handles the download of the image files:
private void imageProcessing(String url, String filename) {
String root = Environment.getExternalStorageDirectory().toString();
// String root1= getResources().getIdentifier(name, defType, defPackage)
File myDir = new File(root + "/arson/images");
File nomedia = new File(myDir, ".nomedia");
if (!nomedia.exists()) {
Log.wtf("nomedia not exists", nomedia.getAbsolutePath().toString());
try {
nomedia.createNewFile();
} catch (IOException e1) {
Log.e("NEW FILE CREATION", e1.toString());
e1.printStackTrace();
}
} else {
Log.wtf("nomedia exists", nomedia.getAbsolutePath().toString());
}
File file = new File(myDir, filename);
if (file.exists()) {
file.delete();
}
try {
Bitmap bitmap = downloadBitmap(url);
myDir.mkdirs();
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
Log.e("BITMAP PROCESS", e.toString());
}
}
public static Bitmap downloadBitmap(String url) {
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
System.setProperty("http.keepAlive", "false");
inputStream = entity.getContent();
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// Could provide a more explicit error message for IOException or
// IllegalStateException
getRequest.abort();
} finally {
if (client != null)
client.close();
}
return null;
}
Thanks in advance!
There are two kind of possible issues here.
1) HTTP Status Code is not 200 : You are returning null if this happens, and when you get null you can know there has been a problem downloading.
2) HTTP Status Code is 200 but file download fails : You will either have an exception here, or none at all. If you have an exception you are already catching it. For the other case where there is no exception you have to change your implementation a little. You will have to save the downloaded file first (temp file), read the contentLength and verify that it matches with what you got from the server. If the contentLength is correct, you can then use BitmapFactory to read the file from the device.