Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing video on texture view with aspect ratio of video

I am playing video from my server on surface using texture view, but its stretching the video and not able maintain aspect ratio of video. But, I wish to maintain aspect ratio as per the video as in vine app or instagram app.

like image 503
Ravish Rajput Avatar asked Dec 11 '14 08:12

Ravish Rajput


3 Answers

You can either change the size of the View (using a custom FrameLayout), or use the TextureView matrix to change the way the texture is rendered.

Examples of both can be found in Grafika. The "Play video (TextureView)" activity demonstrates configuring the matrix to match the aspect ratio of a video. See the adjustAspectRatio() method, the core of which is:

    Matrix txform = new Matrix();
    mTextureView.getTransform(txform);
    txform.setScale((float) newWidth / viewWidth, (float) newHeight / viewHeight);
    txform.postTranslate(xoff, yoff);
    mTextureView.setTransform(txform);

Note it centers as well as scales the video.

like image 148
fadden Avatar answered Nov 10 '22 23:11

fadden


Well I am too late to answer but as I got from Grafika you may use this function

 private void adjustAspectRatio(int videoWidth, int videoHeight) {
    int viewWidth = mTextureView.getWidth();
    int viewHeight = mTextureView.getHeight();
    double aspectRatio = (double) videoHeight / videoWidth;

    int newWidth, newHeight;
    if (viewHeight > (int) (viewWidth * aspectRatio)) {
        // limited by narrow width; restrict height
        newWidth = viewWidth;
        newHeight = (int) (viewWidth * aspectRatio);
    } else {
        // limited by short height; restrict width
        newWidth = (int) (viewHeight / aspectRatio);
        newHeight = viewHeight;
    }
    int xoff = (viewWidth - newWidth) / 2;
    int yoff = (viewHeight - newHeight) / 2;
    Log.v(TAG, "video=" + videoWidth + "x" + videoHeight +
            " view=" + viewWidth + "x" + viewHeight +
            " newView=" + newWidth + "x" + newHeight +
            " off=" + xoff + "," + yoff);

    Matrix txform = new Matrix();
    mTextureView.getTransform(txform);
    txform.setScale((float) newWidth / viewWidth, (float) newHeight / viewHeight);
    //txform.postRotate(10);          // just for fun
    txform.postTranslate(xoff, yoff);
    mTextureView.setTransform(txform);
}
like image 22
Umar Ata Avatar answered Nov 10 '22 23:11

Umar Ata


You can use ExoPlayer https://github.com/google/ExoPlayer# and check the full demo. It maintains the video aspect ratio perfectly.

like image 1
Hugo Gresse Avatar answered Nov 11 '22 00:11

Hugo Gresse