簡體   English   中英

將視頻從相機意圖傳遞到 webView

[英]Pass video from camera intent to webView

我正在嘗試實現啟動視頻意圖的 webview,並將視頻返回到 webView。

我嘗試做的事情:

1)Java - 添加打開視頻捕獲意圖的webAppInterface:

mWebView = (WebView) findViewById(R.id.webView);
mWebView.addJavascriptInterface(webAppInterface, "Android");

public class WebAppInterface {
    ...
    public void dispatchTakeVideoIntent() {
        Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        takeVideoIntent.putExtra(android.provider.MediaStore.EXTRA_DURATION_LIMIT,10);

        if (takePictureIntent.resolveActivity(mContext.getPackageManager()) != null) {
            ((AppCompatActivity) mContext).startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
        }
    }
    ...

2) JavaScript - 從 webview 調用它:

Android.dispatchTakeVideoIntent()

3) Java - 獲取 Uri,並將路徑發送到我的 webview

 public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == Activity.RESULT_OK) {
        Uri videoUri = intent.getData();
        wView.loadUrl("javascript:test('" + videoUri.getPath() + "')");
    }
}

4) JavaScript - 在我的 webView 中獲取路徑

window.test = (videoUriPath) => {
    ...
}

我的問題是,如何訪問視頻?

也許與 go 有完全不同的方式呢?

訪問視頻意味着我假設在 webView 中播放視頻。 在您的 HTML 中有一個視頻元素(假設 id 是“my-video”),那么您的 javascript 將是:

window.test = (videoUriPath) => {
 var video = document.getElementById('video');
 var source = document.createElement('source');

 source.setAttribute('src', videoUriPath);

 video.appendChild(source);
 video.load();
 video.play();
}

好的,我找到了一個解決方案,它有點矯枉過正,但它的工作......

1)JAVA:將視頻轉換為字節數組

byte[] bytes;
byte[] data = new byte[16384];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = is.read(data)) != -1) {
   output.write(data, 0, bytesRead);
}
bytes = output.toByteArray();

2)JAVA:將編碼的塊(base64)發送到webvView

int startIndex = 0;
int chunkSize= 16384;
while(startIndex < bytes.length){
     byte[] newArray = Arrays.copyOfRange(bytes, startIndex, startIndex + chunkSize);
     startIndex = startIndex + chunkSize;
     encodedString = Base64.encodeToString(newArray, Base64.DEFAULT);
     wView.loadUrl("javascript:g_sendFile_f('" + encodedString + "')");
}
wView.loadUrl("javascript:g_sendFile_f('" + "finish" + "')");

3) JAVASCRIPT:接收編碼塊,合並它們,創建blob文件

let bytesArrFinal_an = []
window.g_sendFile_f = (msg) =>{
     // last call
     if(msg === "finish"){
         let blob = new Blob(byteArrFinal_an,{type : "video/mp4"})
         this.test_videoUrl = URL.createObjectURL(blob);
         console.log("finish")
         return
      }

      // add bytes to final array
      let bytesArr_an = this.b64toByteArr(msg)
      bytesArrFinal_an = bytesArrFinal_an.concat(bytesArr_an);
      console.log(msg)
}

如果有人有更優雅的解決方案,我會很高興看到它!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM