I have been compressing Images without any problems. Recently my app required video compress functionality to be added. Again, Silicompressor does the job but for some reason there is no audio in output file.
I am using code inside Runnable
private void compressVideo() {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
new CompressVideo().execute("false",uri.toString(),file.getPath());
// Uri muri = Uri.parse(uri.toString());
}
#SuppressLint("StaticFieldLeak")
private class CompressVideo extends AsyncTask<String,String,String> {
#Override
protected String doInBackground(String... strings) {
String videoPath = null;
try {
Uri mUri = Uri.parse(strings[1]);
videoPath = SiliCompressor.with(PostReelActivity.this).compressVideo(mUri,strings[2]);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return videoPath;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
File file = new File(s);
Uri videoUri = Uri.fromFile(file);
uploadVideo(videoUri);
}
}
Related
I am trying to play DASH video stream, I am using Pallycon service to manage keys. The below code works fine when drmSessionManager set to the ExoPlayerFactory.newSimpleInstance (deprecated) instance, but When I set drmSessionManager seperately for media source, player shows blank screen. And not showing any error in logcat.
public class MainActivity extends AppCompatActivity {
private PallyconEventListener pallyconEventListener = new PallyconEventListener() {
#Override
public void onDrmKeysLoaded(Map<String, String> map) {
}
#Override
public void onDrmSessionManagerError(Exception e) {
}
#Override
public void onDrmKeysRestored() {
}
#Override
public void onDrmKeysRemoved() {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PlayerView playerView = findViewById(R.id.player_view);
String siteId = "XXXX";
String siteKey = "XXXX";
PallyconWVMSDK WVMAgent = null;
try {
WVMAgent = PallyconWVMSDKFactory.getInstance(this);
WVMAgent.init(this, null, siteId, siteKey);
WVMAgent.setPallyconEventListener(pallyconEventListener);
} catch (PallyconDrmException e) {
e.printStackTrace();
} catch (UnAuthorizedDeviceException e) {
e.printStackTrace();
}
// TODO : 2.set content information
UUID drmSchemeUuid = UUID.fromString((C.WIDEVINE_UUID).toString());
Uri uri = Uri.parse("http://www.example.com/index.mpd");
String drmLicenseUrl = "http://license.pallycon.com/ri/licenseManager.do";
String cid = "COOL";
String userId = "lpa";
String ptoken = "";
DrmSessionManager<FrameworkMediaCrypto> drmSessionManager = null;
try {
drmSessionManager = Objects.requireNonNull(WVMAgent).createDrmSessionManagerByToken(drmSchemeUuid, drmLicenseUrl, uri, userId, cid, ptoken, false);
} catch (PallyconDrmException e) {
e.printStackTrace();
}
DataSource.Factory dataSourceFactory = new DefaultHttpDataSourceFactory("cool");
SimpleExoPlayer exoPlayer = new SimpleExoPlayer.Builder(this, new DefaultRenderersFactory(this)).setTrackSelector(new DefaultTrackSelector(this)).build();
playerView.setPlayer(exoPlayer);
MediaSource mediaSource2 = new DashMediaSource.Factory(dataSourceFactory).setDrmSessionManager(drmSessionManager).createMediaSource(uri);
exoPlayer.prepare(mediaSource2);
exoPlayer.setPlayWhenReady(true);
}
}
I am using chat application. Upto Android 28sdk its worked fine but after i refract to androidx am facing this problem please check my code below and error screenshot.
Error Code Image 1
Error Code Image 2
private void compressAndUpload(final Context context, final String child, final File file) {
compressionTask = new AsyncTask<File, Void, String>() {
#Override
protected String doInBackground(File... files) {
String filePathCompressed = null;
Uri originalFileUri = Uri.fromFile(files[0]);
File tempFile = new File(context.getCacheDir(), originalFileUri.getLastPathSegment());
//tempFile = File.createTempFile(originalFileUri.getLastPathSegment(), null, context.getCacheDir());
if (child.equals("images")) {
filePathCompressed = SiliCompressor.with(context).compress(originalFileUri.toString(), tempFile);
} else {
try {
filePathCompressed = SiliCompressor.with(context).compressVideo(files[0].getPath(), context.getCacheDir().getPath());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
if (filePathCompressed == null)
filePathCompressed = "";
return filePathCompressed;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
File compressed = new File(s);
fileUri = Uri.fromFile(compressed.length() > 0 ? compressed : file);
FirebaseStorage storage = FirebaseStorage.getInstance();
if (uploadRef == null)
uploadRef = storage.getReference().child(child).child(fileUri.getLastPathSegment());
if (replace) {
upload();
} else {
checkIfExists();
}
}
};
compressionTask.execute(file);
}
I am trying to compress the video but not able to compress fast way....using follow dependency also silicompressor /Video Compressor and Compressor..
The above list of compressor working fine but taking too much of time based on the video selection (For ex : if i select 2 MB video ~3 to 4 minute taking for compression)
class VideoCompressAsyncTask extends AsyncTask<String, String, String> {
Context mContext;
String path = File path;
File directory = new File(path);
public VideoCompressAsyncTask(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgress();
}
#Override
protected String doInBackground(String... paths) {
String filePath = null;
try {
filePath = SiliCompressor.with(mContext).compressVideo(myUrl, directory.getPath(), 0, 0, 0);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return filePath;
}
#Override
protected void onPostExecute(String compressedFilePath) {
super.onPostExecute(compressedFilePath);
File imageFile = new File(compressedFilePath);
}
}
Taking to much of time for video compression
I'm trying to download multiple pictures using picasso. here's my code:
for(int i=1; i <=20; i++){
String url = img_url + i + "/profile.jpg";
String img_dir = img_dir + i;
Picasso.with(this).load(url).into(picassoImageTarget(getApplicationContext(),img_dir, img_name));
}
Url of the site looks like this:
site.com/img/equipment/1/profile.jpg,
site.com/img/equipment/2/profile.jpg,
site.com/img/equipment/3/profile.jpg
and so on ...
i tried
Picasso.with(this).load(url).into(picassoImageTarget(getApplicationContext(),img_dir, img_name));
without the for loop and it is working. images are not download when i place it inside the loop.
here's my Target
private Target picassoImageTarget(Context context, final String imageDir, final String imageName) {
Log.d("picassoImageTarget", " picassoImageTarget");
ContextWrapper cw = new ContextWrapper(context);
final File directory = cw.getDir(imageDir, Context.MODE_PRIVATE); // path to /data/data/yourapp/app_imageDir
return new Target() {
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
#Override
public void run() {
final File myImageFile = new File(directory, imageName); // Create image file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myImageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i("image", "image saved to >>>" + myImageFile.getAbsolutePath());
}
}).start();
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
if (placeHolderDrawable != null) {}
}
};
}
please help. thanks.
Targets are held in WeakReferences.
You need to hold a reference to the Targets you want to keep to prevent them from being garbage collected.
Maybe your code would look something like:
final class MyLoader {
final ArrayList<Target> targets = new ArrayList<>(20);
void load(...) {
for(...) {
Target target = picassoImageTarget(...);
targets.add(target);
picasso.load(...).into(target); // TODO: Maybe remove from list when complete.
}
}
}
I installed this library to view pdf from a url inside my application but when I click on the file to open it gives me the following error:
I tried looking into ContentResolver but no luck
This is the logcat:
07-26 15:35:45.638 8725-8725/com.focuson.iapp.firstapp E/PDFView: load pdf error
java.io.FileNotFoundException: No content provider: http://pub.mylaravel.eu/assets/user_files/3/file_no_1.pdf
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1093)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:944)
at android.content.ContentResolver.openFileDescriptor(ContentResolver.java:797)
at android.content.ContentResolver.openFileDescriptor(ContentResolver.java:751)
at com.github.barteksc.pdfviewer.DecodingAsyncTask.getSeekableFileDescriptor(DecodingAsyncTask.java:82)
at com.github.barteksc.pdfviewer.DecodingAsyncTask.doInBackground(DecodingAsyncTask.java:61)
at com.github.barteksc.pdfviewer.DecodingAsyncTask.doInBackground(DecodingAsyncTask.java:30)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
My activity is:
public class pdfActivity extends AppCompatActivity {
PDFView pdfView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
pdfView= (PDFView) findViewById(R.id.pdfView);
String url=getIntent().getStringExtra("url");
Log.i("URI-URL",String.valueOf(Uri.parse(url)) );
pdfView.fromUri(Uri.parse(url))
.enableSwipe(true)
.enableDoubletap(true)
.swipeVertical(false)
.defaultPage(1)
.showMinimap(false)
.onLoad(new OnLoadCompleteListener() {
#Override
public void loadComplete(int nbPages) {
}
})
.onPageChange(new OnPageChangeListener() {
#Override
public void onPageChanged(int page, int pageCount) {
}
})
.enableAnnotationRendering(false)
.password(null)
.load();}}
My xml is:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.focuson.iapp.firstapp.page_types.Login.pdfActivity">
<com.github.barteksc.pdfviewer.PDFView
android:id="#+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Seems that this library fails to download files from the internet. Download the file to a temp directory and open it:
if (ActivityCompat.checkSelfPermission(WebViewActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(WebViewActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(WebViewActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
} else {
downloadFile();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE:
downloadFile();
break;
}
}
private void downloadFile() {
progressBar.setVisibility(View.VISIBLE);
DownloadFileTask task = new DownloadFileTask(
WebViewActivity.this,
mURL,
"/download/pdf_file.pdf");
task.startTask();
}
#Override
public void onFileDownloaded() {
progressBar.setVisibility(View.GONE);
File file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ "/download/pdf_file.pdf");
if (file.exists()) {
pdfView.fromFile(file)
//.pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default
.enableSwipe(true)
.swipeHorizontal(true)
.enableDoubletap(true)
.defaultPage(0)
.enableAnnotationRendering(true)
.password(null)
.scrollHandle(null)
.onLoad(new OnLoadCompleteListener() {
#Override
public void loadComplete(int nbPages) {
pdfView.setMinZoom(1f);
pdfView.setMidZoom(5f);
pdfView.setMaxZoom(10f);
pdfView.zoomTo(2f);
pdfView.scrollTo(100,0);
pdfView.moveTo(0f,0f);
}
})
.load();
}
}
public class DownloadFileTask {
public static final String TAG = "DownloadFileTask";
private BaseActivity context;
private GetTask contentTask;
private String url;
private String fileName;
public DownloadFileTask(BaseActivity context, String url, String fileName) {
this.context = context;
this.url = url;
this.fileName = fileName;
}
public void startTask() {
doRequest();
}
private void doRequest() {
contentTask = new GetTask();
contentTask.execute();
}
private class GetTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
int count;
try {
Log.d(TAG, "url = " + url);
URL _url = new URL(url);
URLConnection conection = _url.openConnection();
conection.connect();
InputStream input = new BufferedInputStream(_url.openStream(),
8192);
OutputStream output = new FileOutputStream(
Environment.getExternalStorageDirectory() + fileName);
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onPostExecute(String data) {
context.onFileDownloaded();
}
}
}
Uri is not like URL :here
You must download first the *.pdf file and save to SD and finaly you can open it with Pdfview.
No content provider: http://...
It's not clear where you read that the library can download and display a PDF from a network request. A URI can mean many things, and in this case, it is trying to use a ContentProvider to load a raw PDF file from disk.
You can look at the Github repo for that library for sample usage of the URI.