我正在尝试将视频保存到图库中,以下代码在所有Android版本(除了Android Q)上都可以正常工作:
private void getPath() {
String videoFileName = "video_" + System.currentTimeMillis() + ".mp4";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, videoFileName);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4");
contentValues.put(
MediaStore.MediaColumns.RELATIVE_PATH,
"Movies/" + "Folder");
contentValues.put(MediaStore.Video.Media.IS_PENDING, 1);
Uri collection =
MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
Uri videoUri = resolver.insert(collection, contentValues);
if (videoUri != null) {
try (ParcelFileDescriptor pfd = resolver.openFileDescriptor(videoUri, "w", null)) {
OutputStream outputStream = null;
if (pfd != null) {
outputStream = resolver.openOutputStream(videoUri);
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
contentValues.clear();
contentValues.put(MediaStore.Video.Media.IS_PENDING, 0);
if (videoUri != null) {
resolver.update(videoUri, contentValues, null, null);
}
} else {
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)
+ "/Folder");
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
if (success) {
File videoFile = new File(storageDir, videoFileName);
savedVideoPath = videoFile.getAbsolutePath();
}
}
}
我也尝试使用
getExternalFilesDir()
,但是没有效果,在相册中没有创建视频。String videoFileName = "video_" + System.currentTimeMillis() + ".mp4";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
File imageFile = null;
File storageDir = new File(
getExternalFilesDir(Environment.DIRECTORY_DCIM),
"Folder");
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
if (success) {
imageFile = new File(storageDir, videoFileName);
}
savedVideoPath = imageFile.getAbsolutePath();
我使用第三方库来录制SurfaceView
,该库需要一个路径来保存录制的视频:
mRenderPipeline = EZFilter.input(this.effectBmp)
.addFilter(new GalleryEffects().getEffect(VideoMaker.this, i))
.enableRecord(savedVideoPath, true, false)
.into(mRenderView);
当录制视频结束时,录制的视频会保存在给定路径savedVideoPath
中,在所有安卓版本中都能正常工作,但不包括Android Q。
保存视频后,当我检查时,在相册中得到了一个空白视频。
Application
标签内添加android:requestLegacyExternalStorage="true"
来结束了这个问题。 - Mouaad Abdelghafour AITALI