如何将视频文件发送到Firebase数据库&;Android中的存储?
我正在开发一款照片和视频共享android应用程序,并使用Firebase作为我的数据库和存储设备。在我的ShareActivity中,用户可以选择图像捕获或视频录制并将其发送到数据库+存储。使用图像时,一切正常,但无法发送视频文件。 下面是我的共享活动代码如何将视频文件发送到Firebase数据库&;Android中的存储?,android,firebase,firebase-realtime-database,firebase-storage,Android,Firebase,Firebase Realtime Database,Firebase Storage,我正在开发一款照片和视频共享android应用程序,并使用Firebase作为我的数据库和存储设备。在我的ShareActivity中,用户可以选择图像捕获或视频录制并将其发送到数据库+存储。使用图像时,一切正常,但无法发送视频文件。 下面是我的共享活动代码 private static final String TAG = "Camera Tag"; private DatabaseReference mDatabaseShare; private StorageReference mStor
private static final String TAG = "Camera Tag";
private DatabaseReference mDatabaseShare;
private StorageReference mStorageShare;
private EditText mTitle;
private ImageView mTitleImage;
private Button bShare;
private Button mRecordBtn;
private Uri mFileUri;
private ProgressDialog mProgress;
private VideoView mVideoView;
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Media Files";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share);
mTitle = (EditText) findViewById(R.id.title);
// imageview to start camera
mTitleImage = (ImageView) findViewById(R.id.titleimage);
// pushes data to firebase
bShare = (Button) findViewById(R.id.btnshare);
// Videoview for preview
mVideoView = (VideoView) findViewById(R.id.uservid);
// starts video recording
mRecordBtn = (Button) findViewById(R.id.buttonrecord);
mDatabaseShare = FirebaseDatabase.getInstance().getReference().child("SharedMedia");
mStorageShare = FirebaseStorage.getInstance().getReference();
mDatabaseShare.keepSynced(true);
mProgress = new ProgressDialog(this);
mTitleImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showImagePicker();
}
});
bShare.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
shareMedia();
}
});
mRecordBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
recordVideo();
}
});
}
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
mFileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
// 1- for high quality video
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
private void showImagePicker() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mFileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
private Uri getOutputMediaFileUri(int mediaTypeImage) {
return Uri.fromFile(getOutputMediaFile(mediaTypeImage));
}
// Button click method to send data to firebase
private void shareMedia() {
final String name_title = mTitle.getText().toString().trim();
mProgress.setMessage("Please wait");
mProgress.show();
if (!TextUtils.isEmpty(name_title) && mFileUri != null){
StorageReference filepath = mStorageShare.child("Shared_Media").child(mFileUri.getLastPathSegment());
filepath.putFile(mFileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
DatabaseReference newShare = mDatabaseShare.push();
newShare.child("image").setValue(downloadUrl.toString());
newShare.child("video").setValue(downloadUrl.toString());
mProgress.dismiss();
startActivity(new Intent(ShareActivity.this,MainActivity.class));
}
});
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
private void previewVideo() {
try {
mVideoView.setVideoPath(mFileUri.getPath());
// start playing
mVideoView.start();
} catch (Exception e) {
e.printStackTrace();
}
}
private void previewCapturedImage() {
try {
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(mFileUri.getPath(),
options);
mTitleImage.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", mFileUri);
}
/*
* Here we restore the fileUri again
*/
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
mFileUri = savedInstanceState.getParcelable("file_uri");
}
/*
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
private static final String TAG=“相机标签”;
私有数据库引用mDatabaseShare;
私有存储参考mStorageShare;
私人编辑文本mTitle;
私有ImageView mTitleImage;
私人按钮共享;
专用按钮mRecordBtn;
私有Uri-mFileUri;
私人进程;
私有视频视图;
//活动请求代码
专用静态最终int摄像机\捕获\图像\请求\代码=100;
专用静态最终int摄像机\捕获\视频\请求\代码=200;
公共静态最终int媒体类型图像=1;
公共静态最终int媒体类型视频=2;
//用于存储捕获的图像和视频的目录名
私有静态最终字符串IMAGE\u DIRECTORY\u NAME=“Media Files”;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share);
mTitle=(编辑文本)findViewById(R.id.title);
//imageview启动照相机
mTitleImage=(ImageView)findViewById(R.id.titleimage);
//将数据推送到firebase
b共享=(按钮)findViewById(R.id.btnshare);
//视频预览
mVideoView=(VideoView)findviewbyd(R.id.uservid);
//开始录像
mRecordBtn=(按钮)findViewById(R.id.buttonrecord);
mDatabaseShare=FirebaseDatabase.getInstance().getReference().child(“SharedMedia”);
mStorageShare=FirebaseStorage.getInstance().getReference();
mDatabaseShare.keepSynced(true);
mpprogress=新建进度对话框(此对话框);
mTitleImage.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
showImagePicker();
}
});
bShare.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
共享媒体();
}
});
mRecordBtn.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
录制视频();
}
});
}
私人录影带(){
意向意向=新意向(MediaStore.ACTION\u VIDEO\u CAPTURE);
mFileUri=getOutputMediaFileUri(媒体类型视频);
//设置视频质量
//1-用于高质量视频
意向。putExtra(MediaStore.EXTRA视频质量,1);
intent.putExtra(MediaStore.EXTRA_输出,mFileUri);
//启动视频捕获计划
startActivityForResult(意图、摄像头捕捉、视频、请求、代码);
}
私有void showImagePicker(){
意向意向=新意向(MediaStore.ACTION\u IMAGE\u CAPTURE);
mFileUri=getOutputMediaFileUri(媒体类型图像);
intent.putExtra(MediaStore.EXTRA_输出,mFileUri);
//启动图像捕获计划
startActivityForResult(意图、摄像头捕捉、图像、请求、代码);
}
私有Uri getOutputMediaFileUri(int mediaTypeImage){
返回Uri.fromFile(getOutputMediaFile(mediaTypeImage));
}
//按钮单击方法将数据发送到firebase
私有void共享媒体(){
最终字符串名称_title=mTitle.getText().toString().trim();
mProgress.setMessage(“请稍候”);
mProgress.show();
如果(!TextUtils.isEmpty(name_title)&&mFileUri!=null){
StorageReference filepath=mStorageShare.child(“共享的_媒体”).child(mFileUri.getLastPathSegment());
filepath.putFile(mFileUri).addOnSuccessListener(新的OnSuccessListener(){
@凌驾
成功时公共无效(UploadTask.TaskSnapshot TaskSnapshot){
Uri downloadUrl=taskSnapshot.getDownloadUrl();
DatabaseReference newShare=mDatabaseShare.push();
newShare.child(“image”).setValue(downloadUrl.toString());
newShare.child(“视频”).setValue(downloadUrl.toString());
mProgress.disclose();
startActivity(新意图(ShareActivity.this、MainActivity.class));
}
});
}
}
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
if(requestCode==摄像机捕捉图像请求代码){
if(resultCode==RESULT\u OK){
//成功捕获图像
//在图像视图中显示它
previewCapturedImage();
}else if(resultCode==RESULT\u取消){
//用户取消图像捕获
Toast.makeText(getApplicationContext(),
“用户已取消图像捕获”,Toast.LENGTH\u SHORT)
.show();
}否则{
//未能捕获图像
Toast.makeText(getApplicationContext(),
“抱歉!未能捕获图像”,Toast.LENGTH\u SHORT)
.show();
}
}else if(requestCode==摄像机、视频、请求、代码){
if(resultCode==RESULT\u OK){
//录影成功
//预览录制的视频
预览视频();
}else if(resultCode==RESULT\u取消){
//用户取消录制
Toast.makeText(getApplicationContext(),
“用户已取消视频录制”,Toast.LENGTH\u SHORT)
.show();
}否则{
//无法录制视频
Toast.makeText(getApplicationContext(),
“抱歉!录制视频失败”,Toast.LENGTH\u SHORT)
.show();
}
}
}
私有void previewVideo(){
试一试{
mVideoView.setVideoPath(mFileUri.getPath());
//开始玩
mVideoView.start();
}捕获(例外e){
e、 printStackTrace();
}
}
私有无效预览