developer tip

Android의 VideoView에서 비디오 재생

optionbox 2020. 12. 31. 08:11
반응형

Android의 VideoView에서 비디오 재생


내 VideoView에서 비디오를 재생할 수없는 이유를 알 수 없습니다. 내가받는 메시지는 다음과 같습니다.

동영상을 재생할 수 없습니다 : 죄송합니다.이 동영상을 재생할 수 없습니다.

에뮬레이터 용 SD 카드도 만들었습니다. SDK의 특정 폴더에 SD 카드를 넣어야합니까? 의견을주세요.

레이아웃은 다음과 같습니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
   android:id="@+id/LinearLayout01"
   android:layout_height="fill_parent"     
   android:paddingLeft="2px"
   android:paddingRight="2px"
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:paddingTop="2px"
   android:paddingBottom="2px"
   android:layout_width="fill_parent"
   android:orientation="vertical">

      <VideoView 
         android:layout_height="fill_parent"
         android:layout_width="fill_parent" 
         android:id="@+id/VideoView" />

</LinearLayout>

코드는 다음과 같습니다.

package com.examples.videoviewdemo;

import android.app.Activity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class VideoViewDemo extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        VideoView videoView = (VideoView)findViewById(R.id.VideoView);
        //MediaController mediaController = new MediaController(this);
        // mediaController.setAnchorView(videoView);
        //videoView.setMediaController(mediaController);

        videoView.setVideoPath("/sdcard/blonde_secretary.3gp");

        videoView.start();  
    }
}

답장을 기다리는 중 ...


내 생각 엔 동영상이 Android와 호환되지 않는 것 같습니다. 다른 비디오로 시도해보십시오. 이것은 확실히 Android에서 작동 하는 데 사용되었지만 새로운 장치에서는 작동하지 않습니다. 해당 동영상은 작동하지만 귀하의 동영상은 작동하지 않는 경우 동영상이 Android와 호환되지 않는 것입니다.

다른 사람들이 지적했듯이 장치에서 이것을 테스트하십시오. 에뮬레이터에서 비디오를 재생하려면 너무 많은 전력이 필요합니다.


예제 프로젝트

마침내 작업 할 개념 증명 프로젝트를 얻었으므로 여기서 공유하겠습니다.

레이아웃 설정

레이아웃은 이와 같이 설정되며 밝은 회색 영역은 VideoView.

enter image description here

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.videotest.MainActivity">

    <VideoView
        android:id="@+id/videoview"
        android:layout_width="300dp"
        android:layout_height="200dp"/>

    <Button
        android:text="Play"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/videoview"
        android:onClick="onButtonClick"
        android:id="@+id/button"/>

</RelativeLayout>

비디오 클립 준비

문서 에 따르면 Android는 모든 API 레벨에 대해 mp4 H.264 재생 (디코딩)을 지원해야합니다. 하지만 실제 영상의 재생 여부에 영향을 미치는 요인이 많은 것 같습니다. 비디오 인코딩 방법을 알려주는 가장 심층적 인 답변은 여기에 있습니다 . 강력한 ffmpeg명령 줄 도구를 사용하여 모든 Android 기기에서 재생할 수 있어야하는 것으로 변환합니다. 자세한 설명은 내가 링크 한 답변을 읽으십시오. 원래 버전에서 오류가 발생했기 때문에 약간 수정 된 버전을 사용했습니다.

ffmpeg -y -i input_file.avi -s 432x320 -b:v 384k -vcodec libx264 -flags +loop+mv4 -cmp 256 -partitions +parti4x4+parti8x8+partp4x4+partp8x8 -subq 6 -trellis 0 -refs 5 -bf 0 -coder 0 -me_range 16 -g 250 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -qmin 10 -qmax 51 -qdiff 4 -c:a aac -ac 1 -ar 16000 -r 13 -ab 32000 -aspect 3:2 -strict -2 output_file.mp4

비디오 및 오디오 품질에 관한 한 조정이 필요한지 확인하기 위해 각 매개 변수에 대해 더 많이 읽었습니다.

다음으로 이름 output_file.mp4바꾸고 test.mp4Android 프로젝트 /res/raw폴더 에 넣으십시오 . 아직 존재하지 않는 경우 폴더를 만듭니다.

암호

코드는 많지 않습니다. "재생"버튼을 클릭하면 비디오가 재생됩니다. 이 답변감사드립니다 .

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onButtonClick(View v) {
        VideoView videoview = (VideoView) findViewById(R.id.videoview);
        Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.test);
        videoview.setVideoURI(uri);
        videoview.start();
    }
}

끝마친

그게 다야. 이제 시뮬레이터 또는 실제 장치에서 비디오 클립을 재생할 수 있습니다.


함수에 videoView로컬로 유지하는 대신 활동 클래스의 멤버 변수를 만듭니다 onCreate.

VideoView videoView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    videoView = (VideoView)findViewById(R.id.VideoView);        
    videoView.setVideoPath("/sdcard/blonde_secretary.3gp");
    videoView.start();  
}

android.permission.READ_EXTERNAL_STORAGE를 매니페스트에 추가하고 나를 위해 일했습니다.


The code seems to be flawless! Simple and plain.
So it should work on the phone. The emulator is having hard time playing videos, it happened to me too.

Try increasing the required API level to the latest, it might help!

Right click on opened project, chose Properties > Android > check the latest version on the right side...

Igor


You can access your SD card via the DDMS


To confirm you video is in the correct format (resolution, bitrate, codec, etc.) check with the official documentation - extract below:

Standard definition (Low quality)
Video codec - H.264
Video resolution - 176 x 144 px
Video frame rate - 12 fps
Video bitrate - 56 Kbps
Audio codec - AAC-LC
Audio channels - (mono)
Audio bitrate - 24 Kbps

Standard definition (High quality)
Video codec - H.264
Video resolution - 480 x 360 px
Video frame rate - 30 fps
Video bitrate - 500 Kbps
Audio codec - AAC-LC
Audio channels - 2 (stereo)
Audio bitrate - 128 Kbps

High definition 720p (N/A on all devices)
Video codec - H.264
Video resolution - 1280 x 720 px
Video frame rate - 30 fps
Video bitrate - 2 Mbps
Audio codec - AAC-LC
Audio channels - 2 (stereo)
Audio bitrate - 192 Kbps


VideoView videoView =(VideoView) findViewById(R.id.videoViewId);

Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+"/yourvideo");

 videoView.setVideoURI(uri);
videoView.start();

Instead of using setVideoPath use setVideoUri. you can get path of your video stored in external storage by using (Environment.getExternalStorageDirectory().getAbsolutePath()+"/yourvideo")and parse it into Uri. If your video is stored in sdcard/MyVideo/video.mp4 replace "/yourvideo" in code by "/MyVideo/video.mp4"

This works fine for me :) `


VideoView can only Stream 3gp videos I recommend this code to stream your video or try a higher version of android. Try Video Online Streaming.

public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.main);
    String videourl = "http://something.com/blah.mp4";
    Uri uri = Uri.parse(videourl);
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    intent.setDataAndType(uri, "video/mp4");
    startActivity(intent);
}

Or Click here to watch Android Video Streaming Tutorial.


Well ! if you are using a android Compatibility Video then the only cause of this alert is you must be using a video sized more then the 300MB. Android doesn't support large Video (>300MB). We can get it by using NDK optimization.


I have almost same issue with VideoView. I try to play a video (1080*1080) with a Nexus 5 and it works well, but the same video on Galaxy ace 2 give me the Cannot Play Video message.

But I notice that with a lower definition of the video (120x120), it works fine.

So perhaps just a matter of "Size" (and especially with blonde_secretary.3gp video ....)


//just copy this code to your main activity.

 if ( ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ){
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)){

            }else {
                ActivityCompat.requestPermissions(MainActivity.this,new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},1);
            }
        }else {
        }

The problem might be with the Movie format. If it's H264 encoded, make sure it's in baseline profile.

ReferenceURL : https://stackoverflow.com/questions/3263736/playing-a-video-in-videoview-in-android

반응형