studio reales proyectos programacion libro introducción incluye herramientas fundamentos fuente español código con avanzado aplicaciones java android fullscreen videoview

java - reales - Videoview en pantalla completa sin estirar el video



libro de android studio en español pdf (6)

Me pregunto si puedo obtener una forma de permitir que el video se ejecute a través de videoview en pantalla completa.

Busqué mucho e intenté de muchas maneras, como por ejemplo:

  1. Aplicar tema en manifiesto:

    android:theme="@android:style/Theme.NoTitleBar.Fullscreen"

    pero eso no obliga al video a estar en pantalla completa.

  2. Aplicar en la actividad en sí:

    requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    tampoco obliga al video a estar en pantalla completa.

La única forma de forzar el video a pantalla completa es:

<VideoView android:id="@+id/myvideoview" android:layout_width="fill_parent" android:layout_alignParentRight="true" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_alignParentBottom="true" android:layout_height="fill_parent"> </VideoView>

De esta manera resulta en un video de pantalla completa pero extiende el video en sí (video alargado),

No estoy aplicando esta solución incorrecta a mi videoview, entonces ¿hay alguna manera de hacerlo sin estirar el video?

Clase de video:

public class Video extends Activity { private VideoView myvid; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); myvid = (VideoView) findViewById(R.id.myvideoview); myvid.setVideoURI(Uri.parse("android.resource://" + getPackageName() +"/"+R.raw.video_1)); myvid.setMediaController(new MediaController(this)); myvid.requestFocus(); myvid.start(); } }

main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <VideoView android:id="@+id/myvideoview" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout>


¿Has intentado ajustar el tamaño del soporte de superficie subyacente? Pruebe con el código que se muestra a continuación, debe ajustar el soporte de superficie para que tenga el mismo ancho y altura del tamaño de la pantalla. Aún debe tener su actividad a pantalla completa sin una barra de título.

public class Video extends Activity { private VideoView myvid; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); myvid = (VideoView) findViewById(R.id.myvideoview); myvid.setVideoURI(Uri.parse("android.resource://" + getPackageName() +"/"+R.raw.video_1)); myvid.setMediaController(new MediaController(this)); myvid.requestFocus(); //Set the surface holder height to the screen dimensions Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); myvid.getHolder().setFixedSize(size.x, size.y); myvid.start(); } }


Bueno, espero que ayude a FullscreenVideoView

Maneja todo el código aburrido sobre la vista de superficie y la vista de pantalla completa y le permite enfocarse solo en los botones de la IU.

Y puede usar FullscreenVideoLayout si no desea crear sus botones personalizados.


De esta manera, puede establecer las propiedades del video usted mismo.

Use SurfaceView (le da más control sobre la vista), configúrelo en fill_parent para que coincida con toda la pantalla

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="fill_parent"> <SurfaceView android:id="@+id/surfaceViewFrame" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="center" > </SurfaceView> </Linearlayout>

Luego, en su código java, obtenga la vista de superficie y agregue su reproductor multimedia.

surfaceViewFrame = (SurfaceView) findViewById(R.id.surfaceViewFrame); player = new MediaPlayer(); player.setDisplay(holder);

configura en tu reproductor un OnPreparedListener y calcula manualmente el tamaño deseado del video, para llenar la pantalla en la proporción deseada, evitando estirar el video.

player.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { // Adjust the size of the video // so it fits on the screen int videoWidth = player.getVideoWidth(); int videoHeight = player.getVideoHeight(); float videoProportion = (float) videoWidth / (float) videoHeight; int screenWidth = getWindowManager().getDefaultDisplay().getWidth(); int screenHeight = getWindowManager().getDefaultDisplay().getHeight(); float screenProportion = (float) screenWidth / (float) screenHeight; android.view.ViewGroup.LayoutParams lp = surfaceViewFrame.getLayoutParams(); if (videoProportion > screenProportion) { lp.width = screenWidth; lp.height = (int) ((float) screenWidth / videoProportion); } else { lp.width = (int) (videoProportion * (float) screenHeight); lp.height = screenHeight; } surfaceViewFrame.setLayoutParams(lp); if (!player.isPlaying()) { player.start(); } } });

Modifiqué esto de un tutorial para la transmisión de video que seguí hace algún tiempo, no lo puedo encontrar ahora mismo para hacer referencia, si alguien lo tiene, ¡por favor agregue el enlace a la respuesta!

¡Espero eso ayude!

EDITAR

Ok, entonces, si quieres que el video ocupe toda la pantalla y no quieras que se estire, terminarás con rayas negras en los lados. En el código que publiqué, descubrimos qué es más grande, el video o la pantalla del teléfono y lo adaptamos de la mejor manera posible.

Allí tienes toda mi actividad, transmitiendo un video desde un enlace. Es 100% funcional. No puedo decirte cómo reproducir un video desde tu dispositivo porque no lo sé. Estoy seguro de que lo encontrará en la documentación here o here .

public class VideoPlayer extends Activity implements Callback, OnPreparedListener, OnCompletionListener, OnClickListener { private SurfaceView surfaceViewFrame; private static final String TAG = "VideoPlayer"; private SurfaceHolder holder; private ProgressBar progressBarWait; private ImageView pause; private MediaPlayer player; private Timer updateTimer; String video_uri = "http://daily3gp.com/vids/familyguy_has_own_orbit.3gp"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.videosample); pause = (ImageView) findViewById(R.id.imageViewPauseIndicator); pause.setVisibility(View.GONE); if (player != null) { if (!player.isPlaying()) { pause.setVisibility(View.VISIBLE); } } surfaceViewFrame = (SurfaceView) findViewById(R.id.surfaceViewFrame); surfaceViewFrame.setOnClickListener(this); surfaceViewFrame.setClickable(false); progressBarWait = (ProgressBar) findViewById(R.id.progressBarWait); holder = surfaceViewFrame.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); player = new MediaPlayer(); player.setOnPreparedListener(this); player.setOnCompletionListener(this); player.setScreenOnWhilePlaying(true); player.setDisplay(holder); } private void playVideo() { new Thread(new Runnable() { public void run() { try { player.setDataSource(video_uri); player.prepare(); } catch (Exception e) { // I can split the exceptions to get which error i need. showToast("Error while playing video"); Log.i(TAG, "Error"); e.printStackTrace(); } } }).start(); } private void showToast(final String string) { runOnUiThread(new Runnable() { public void run() { Toast.makeText(VideoPlayer.this, string, Toast.LENGTH_LONG).show(); finish(); } }); } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub } public void surfaceCreated(SurfaceHolder holder) { playVideo(); } public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub } //prepare the video public void onPrepared(MediaPlayer mp) { progressBarWait.setVisibility(View.GONE); // Adjust the size of the video // so it fits on the screen int videoWidth = player.getVideoWidth(); int videoHeight = player.getVideoHeight(); float videoProportion = (float) videoWidth / (float) videoHeight; int screenWidth = getWindowManager().getDefaultDisplay().getWidth(); int screenHeight = getWindowManager().getDefaultDisplay().getHeight(); float screenProportion = (float) screenWidth / (float) screenHeight; android.view.ViewGroup.LayoutParams lp = surfaceViewFrame.getLayoutParams(); if (videoProportion > screenProportion) { lp.width = screenWidth; lp.height = (int) ((float) screenWidth / videoProportion); } else { lp.width = (int) (videoProportion * (float) screenHeight); lp.height = screenHeight; } surfaceViewFrame.setLayoutParams(lp); if (!player.isPlaying()) { player.start(); } surfaceViewFrame.setClickable(true); } // callback when the video is over public void onCompletion(MediaPlayer mp) { mp.stop(); if (updateTimer != null) { updateTimer.cancel(); } finish(); } //pause and resume public void onClick(View v) { if (v.getId() == R.id.surfaceViewFrame) { if (player != null) { if (player.isPlaying()) { player.pause(); pause.setVisibility(View.VISIBLE); } else { player.start(); pause.setVisibility(View.GONE); } } } } }


Lo he resuelto por Custom VideoView :

He agregado VideoView a ParentView de dos maneras Desde xml y programáticamente.

Agregue clase personalizada para VideoView nombrado con FullScreenVideoView.java :

import android.content.Context; import android.util.AttributeSet; import android.widget.VideoView; public class FullScreenVideoView extends VideoView { public FullScreenVideoView(Context context) { super(context); } public FullScreenVideoView(Context context, AttributeSet attrs) { super(context, attrs); } public FullScreenVideoView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){ super.onMeasure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(widthMeasureSpec, heightMeasureSpec); } }

Cómo enlazar con xml :

<FrameLayout android:id="@+id/secondMedia" android:layout_width="match_parent" android:layout_height="match_parent"> <com.my.package.customview.FullScreenVideoView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/fullScreenVideoView"/> </FrameLayout>

O

Cómo agregar Programemente VideoView a ParentView :

FullScreenVideoView videoView = new FullScreenVideoView(getActivity()); parentLayout.addView(videoView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));

Espero que esto te ayudará.


Un SurfaceView le proporciona una superficie de dibujo optimizada

public class YourMovieActivity extends Activity implements SurfaceHolder.Callback { private MediaPlayer media = null; //... @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); media = new MediaPlayer(); mSurfaceView = (SurfaceView) findViewById(R.id.surface); //... } }

Las llamadas de MediaPlayer se deben envolver en una prueba {}.

@Override public void surfaceCreated(SurfaceHolder holder) { media.setDataSource("android.resource://" + getPackageName() +"/"+R.raw.video_); media.prepare(); int videoWidth = mp.getVideoWidth(); int videoHeight = mp.getVideoHeight(); int screenWidth = getWindowManager().getDefaultDisplay().getWidth(); android.view. ViewGroup.LayoutParams layout = mSurfaceView.getLayoutParams(); layout.width = screenWidth; layout.height = (int) (((float)videoHeight / (float)videoWidth) * (float)screenWidth); mSurfaceView.setLayoutParams(layout); mp.start(); }


@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); videoView1 = (VideoView) findViewById(R.id.videoview); String SrcPath = "/mnt/sdcard/final.mp4"; videoView1.setVideoPath(SrcPath); videoView1.setMediaController(new MediaController(this)); videoView1.requestFocus(); videoView1.start(); } } <VideoView android:id="@+id/videoview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" > </VideoView>

intenta esto, me está funcionando