Polyv Help Center

Help Center

4 Video Playback

Updated: 2026-01-07 17:41:36

1. Pre-Playback Preparation

1.1 Deploying the Player

PolyvVideoView is the main View class of the video player, which controls video playback, progress, etc. To implement video playback functionality, simply add the layout and call videoView.setVid(vid). Calling the setVid(vid) method will automatically start video playback. Code example:

<RelativeLayout
        android:id="@+id/view_layout"
        android:layout_width="match_parent"
        android:layout_height="@dimen/top_center_player_height"
        android:background="@color/top_text_color_black">

        <com.easefun.polyvsdk.video.PolyvVideoView
            android:id="@+id/polyv_video_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
   
        ...
</RelativeLayout>
PolyvVideoView videoView = findViewById(R.id.polyv_video_view);
videoView.setVid(vid);

Additionally, there are more overloaded methods that support additional playback settings. For example:

videoView.setVid(videoId, isMustFromLocal);//是否播放本地视频。本地存在视频id的文件,并且是完整的就播放
videoView.setVid(videoId, bitRate);//设置视频id,播放对应码率的视频。
videoView.setVidWithStudentId(videoId,studentId);//指定观众的id,播放视频
//播放外部视频
videoView.setVideoPath(path);//设置视频路径,如网址URL。
...

1.2 External Playback Credential

Starting from VOD SDK version 2.17.0, it supports playing encrypted videos by passing a playback credential externally, to prevent illegal pirates from exploiting vulnerabilities to create playback credentials without identity information.

  • The Token is used to decrypt videos encrypted by POLYV platform. Passing the Token locally will better enhance video security.
  • When using this feature, customers must ensure the security of the Token during transmission in their own API, such as API encryption.

First, you need to integrate the VOD SDK version 2.17.0 or above.

Second, during player initialization, call the setVideoTokenRequestListener method to set the callback listener and pass the playback credential.

videoView.setVideoTokenRequestListener(new IPLVVideoTokenRequestListener() {
    @Override
    public String onRequestToken(PolyvVideoVO videoVO, String viewerId, String viewerName, String viewerParam) {
        // 返回外部获取的 token
        // 注意:此处如果为异步请求token,需要将线程等待,待请求结果返回后,再进行return
        // 可参考使用CountDownLatch进行线程等待
        return token;
    }
});

The playback credential should be obtained through your custom API. For backend developers' API development and the full process of playing encrypted videos, please refer to Best Practices for Playing Encrypted Videos.

2. Basic Settings

Before formally using the player, we should configure the basic properties of PolyvVideoView to make the video player more suitable for the developer's design and usage. Some settings are as follows. For more settings, see the API Documentation.

2.1 Auto Play

Set whether to auto-play. Default is auto-play.

setAutoPlay(boolean isAutoPlay)

2.2 Auto Resume

Set whether to auto-resume playback. Default is off. When enabled, re-entering the video will continue playback from the last position.

setAutoContinue(boolean isAutoContinue)

2.3 Enable Ads

Set whether to enable ads. Default is off.

setOpenAd(boolean isOpenAd)

2.4 Enable Subtitles

Set whether to enable subtitles. Default is off.

setOpenSRT(boolean isOpenSRT)

2.5 Enable Preloading

Set whether to enable preloading. Default is off.

setOpenPreload(boolean isOpenPreload)

2.6 Enable Marquee

Set whether to enable the marquee. Default is off.

setOpenMarquee(boolean isOpenMarquee)

2.7 Enable Gestures

Set whether gestures are needed. Default is off. When enabled, setting a gesture listener will trigger callbacks.

setNeedGestureDetector(boolean need)

2.8 Enable Screen Recording Prevention

Set whether to enable screen recording prevention. Default is off. If screen recording prevention is enabled, the screen casting feature will be unavailable.

disableScreenCAP(Activity activity, boolean disableScreenCAP)

2.9 Set Loading Timeout

Set the loading timeout. Default is off, minimum 25 seconds.

setLoadTimeoutSecond(int timeoutSecond)//设置后自动开启
setLoadTimeoutSecond(boolean isOpenLoadTimeout, int timeoutSecond)

2.10 Set Buffering Timeout

Set the buffering timeout. Default is off, minimum 15 seconds.

setBufferTimeoutSecond(int timeoutSecond)
setBufferTimeoutSecond(boolean isOpenBufferTimeout, int timeoutSecond)

2.11 Set Background Playback

In PolyvPlayerActivity, there is a field isBackgroundPlay that controls whether background playback is allowed. Default is not allowed.

private boolean isBackgroundPlay = false;//默认不允许后台播放

Note that we do not handle background keep-alive separately; developers need to add relevant logic themselves.

Starting from SDK 2.11.0, the keep-alive logic of starting a foreground service when entering background playback is implemented, and background playback is allowed by default.

2.12 Set Preload Duration

Set the preload duration for the video. It provides two methods: setting the maximum cache byte size and setting the maximum cache time.

setMaxCacheSize(long maxBuffer)
setMaxCacheDuration(int cacheDuration)

3. Advanced Settings

3.1 Set Resolution

Set the bitrate, i.e., set the resolution. The parameter passed is an enum type from PolyvBitRate.java.

/**
* @param bitRate :
* 0-自动, 1-流畅, 2-高清, 3-超清
*/
changeBitRate(int bitRate)
changeBitRate(int bitRate, boolean isMustFromLocal)
changeBitRate(int bitRate, @PolyvPlayStrategy.PlayStrategy int strategy)

3.2 Route Switching

Route switching refers to switching the CDN service provider accessed by the video. POLYV provides multiple route switching for encrypted VOD. You can know the number of available switchable routes through getRouteCount(). The value of route is greater than or equal to 1.

changeRoute(final int route)//切换线路
getRouteCount()//获取线路源数量

3.3 Set Playback Speed

The player supports speed playback. The normal playback speed is 1.0. Developers can modify this value to change the playback speed. It is recommended not to exceed 2.0 for speed playback.

setSpeed(float speed)//设置播放速度
getSpeed()//获取当前播放速度

3.4 Set Playback Volume

Set the playback volume. The value range is [0, 100].

closeSound()//关闭声音
openSound()//开启声音
setVolume(int volume)//设置音量
getVolume()//获取当前音量

3.5 Seek Playback Progress

Jump to a specific time point in the video, in milliseconds. For example, to jump to 2 seconds from the start videoView.seekTo(2000).

seekTo(int pos)//跳转进度

3.6 Set Video Stretch Mode

setAspectRatio(int screen)

PolyvPlayerScreenRatio.java defines the optional screen ratio modes:

Stretch Mode Description
AR_ASPECT_FIT_PARENT Scale proportionally
AR_ASPECT_FILL_PARENT Fill parent view
AR_ASPECT_WRAP_CONTENT Match content
AR_MATCH_PARENT Fit parent view
AR_16_9_FIT_PARENT 16:9 scale
AR_4_3_FIT_PARENT 4:3 scale

3.7 Audio / Video Mode Switching

Controls whether the player plays audio or video. Default is video playback mode. Optional parameter is PolyvVideoVO.MODE_VIDEO [视频模式] | PolyvVideoVO.MODE_AUDIO [音频模式].

changeMode(String priorityMode)
getCurrentMode()//获取当前播放模式,视频模式或音频模式
setPriorityMode(String priorityMode)//设置优先模式

There are two ways to play audio:

One is to play an MP3 source file in video mode. Since it is video mode, the player will have no picture by default. In the demo, the audio mode UI is displayed in this case. Developers can customize it.

videoView.setOnPreparedListener(new IPolyvOnPreparedListener2() {
    @Override
    public void onPrepared() {
        if (videoView.getVideo() != null && videoView.getVideo().isMp3Source()) {
            audioSourceCoverView.onlyShowCover(videoView);
        } else {
            audioSourceCoverView.hide();
        }
        //...
    }
});

The other is to switch to audio mode. For videos that support audio/video switching, directly use the changeMode() method to switch to audio mode playback. To generate videos that support audio/video switching, you need to contact the administrator to enable the relevant feature. After enabling, you can control the switch in the backend video settings. When enabled, an additional audio file will be generated during video transcoding, allowing the player to switch between audio and video.

3.8 Set Seek Precision Mode and Seek Strategy

The player's Seek mode is divided into two types, controlling whether the seek accurately slides to the corresponding time point:

  • PolyvSeekType.SEEKTYPE_NORMAL: Normal mode, seeks based on keyframes. The player internally retrieves video information, extracts keyframes, and the seek position is determined by the keyframe position.
  • PolyvSeekType.SEEKTYPE_ACCURATE: Precision mode. The player internally processes and analyzes, seeking accurately to the second, which is more precise than normal mode. However, resource consumption also increases.
videoView.setSeekType(PolyvSeekType.SEEKTYPE_NORMAL);

Additionally, starting from version 2.12.1, the demo adds Seek strategy configuration control. Developers can refer to or directly use the implementation to disable dragging on the Seek progress bar, etc. Developers only need to set dragSeekStrategy to the desired configuration. The default is DRAG_SEEK_PLAYED, which only allows dragging to jump playback progress within the played area.

//PolyvPlayerMediaController.java
//进度条拖拽跳转播放进度策略
public static final int DRAG_SEEK_ALLOW = 0;//允许拖动进度条跳转进度
public static final int DRAG_SEEK_BAN = 1;//禁止拖动进度条跳转进度
public static final int DRAG_SEEK_PLAYED = 2;//只允许在已播放进度区域拖动跳转播放进度
private int dragSeekStrategy = DRAG_SEEK_PLAYED;

4. Playback Status

4.1 Pause and Resume Playback

Use the start() method to change the playback status to resume. Note that you must first call the setVid(vid) method, because the start() method does not set a video source, and calling start() directly is invalid. It only changes the playback status to resume. Combined with the pause() method, you can implement pause/resume functionality.

start()//开始播放
pause()//暂停播放
pause(boolean isNotShowAdvert)//暂停的时候是否显示广告
isPlaying()//是否正在播放

Additionally, in the basic settings, enabling auto-resume allows automatically jumping to the last progress when re-entering the same video.

setAutoContinue(true)//开启自动续播

4.2 Media Duration and Buffer Progress

The media duration is returned in milliseconds. Use getCurrentPosition() to get the current playback progress. For example, if a video has played for 2 seconds, then videoView.getCurrentPosition() = 2000.

getCurrentPosition()//取得视频播放进度当前位置
getDuration()//获取总时长

Use getBufferPercentage() to get the current buffer progress percentage. Additionally, you can set the maximum cache bytes, default is 15M.

getBufferPercentage()//当前缓冲百分比
setMaxBuffer(long maxBuffer)//设置最大缓存字节,默认15M

4.3 Capture Current Frame Screenshot

screenshot()

4.4 Gesture Interaction

The player supports recognizing 8 types of gestures and exposes the recognized gesture types and response event callbacks. Developers can implement gesture events according to actual needs. All callbacks are made on the main thread. For specific implementation, refer to the demo's PolyvPlayerActivity.

interface IPolyvOnGestureRightUpListener;//手势右向上滑动
interface IPolyvOnGestureRightDownListener;//手势右向下滑动
interface IPolyvOnGestureLeftUpListener;//手势左向上滑动
interface IPolyvOnGestureLeftDownListener;//手势左向下滑动
interface IPolyvOnGestureSwipeLeftListener;//手势向左滑
interface IPolyvOnGestureSwipeRightListener;//手势向右滑
interface IPolyvOnGestureClickListener;//单击
interface IPolyvOnGestureDoubleClickListener;//双击

The following example sets the brightness to increase when swiping left and up:

videoView.setOnGestureLeftUpListener(new IPolyvOnGestureLeftUpListener() {
    @Override
    public void callback(boolean start, boolean end) {
        if(mediaController.isLocked()){
            return;
        }
        int brightness = videoView.getBrightness(PolyvPlayerActivity.this) + 5;
        if (brightness > 100) {
            brightness = 100;
        }
        videoView.setBrightness(PolyvPlayerActivity.this, brightness);
        lightView.setViewLightValue(brightness, end);
    }
});

4.5 Status Callbacks

Under the com.easefun.polyvsdk.video.listener package, more callback listeners are available, which can be set to the player to monitor player status. Only a partial list of callbacks is shown here. For details, see the API Documentation.

  • Video ready to play callback

    public interface IPolyvOnPreparedListener2 {
        @MainThread
        void onPrepared();
    }
    
  • Video completion callback

    public interface IPolyvOnCompletionListener2 {
        @MainThread
        void onCompletion();
    }
    
  • Video player error callback

    public interface IPolyvOnVideoPlayErrorListener2 {
        @MainThread
        boolean onVideoPlayError(@PolyvPlayErrorReason.PlayErrorReason int errorReason);
    }
    
  • Buffer update callback

    public interface IPolyvOnBufferingUpdateListener2 {
        @MainThread
        void onBufferingUpdate(int percent);
    }
    
  • Seek completion callback

    public interface IPolyvOnSeekCompleteListener2 {
        @MainThread
        void onSeekComplete();
    }
    
  • ...

5. Custom Player Controls

5.1 Player Control Bar

The player control bar allows us to conveniently control player playback and switch player states, such as selecting resolution, controlling volume, etc. A custom player control bar interface needs to inherit from the PolyvBaseMediaController class, similar to the system player. After initialization, it is passed as a parameter to PolyvVideoView. The following is an example from the demo:

//PolyvPlayerMediaController 是demo中自定义的播放器控制栏,具体实现请查看demo
PolyvPlayerMediaController mediaController = findViewById(R.id.polyv_player_media_controller);
...
videoView.setMediaController(mediaController);

It is recommended that only developers with sufficient ability customize the player control bar interface. The demo contains a complete example of the player control bar interface.

5.2 Set Auxiliary Video

Auxiliary videos can be used to play ads, intros, etc. PolyvAuxiliaryVideoView is its main implementation class. Its basic usage is similar to PolyvVideoView. After initialization, it is passed as a parameter to PolyvVideoView. Note that the ad setting must be enabled for it to take effect videoView.setOpenAd(true).

<com.easefun.polyvsdk.video.auxiliary.PolyvAuxiliaryVideoView
    android:id="@+id/polyv_auxiliary_video_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black" />
PolyvAuxiliaryVideoView auxiliaryVideoView = findViewById(R.id.polyv_auxiliary_video_view);
videoView.setAuxiliaryVideoView(auxiliaryVideoView);

For more related settings, see the API Documentation com.easefun.polyvsdk.video.auxiliary section. For specific implementation, refer to the demo's PolyvPlayerActivity related settings.

5.3 Marquee

The marquee allows scrolling text to be displayed during video playback, commonly used as an anti-piracy watermark. The Polyv SDK provides a built-in marquee implementation. It mainly uses PolyvMarqueeView as the display View and sets marquee properties through PolyvMarqueeItem.

<RelativeLayout
        ...>

        <com.easefun.polyvsdk.video.PolyvVideoView
            android:id="@+id/polyv_video_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    
        <com.easefun.polyvsdk.marquee.PolyvMarqueeView
            android:id="@+id/polyv_marquee_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
   
        ...
</RelativeLayout>
//开启跑马灯
videoView.setOpenMarquee(true);
// 设置跑马灯
videoView.setMarqueeView(marqueeView, marqueeItem = new PolyvMarqueeItem()
                         .setStyle(PolyvMarqueeItem.STYLE_ROLL) //样式
                         .setDuration(10000) //时长
                         .setText("POLYV Android SDK") //文本
                         .setSize(16) //字体大小
                         .setColor(Color.YELLOW) //字体颜色
                         .setTextAlpha(70) //字体透明度
                         .setInterval(1000) //隐藏时间
                         .setLifeTime(1000) //显示时间
                         .setTweenTime(1000) //渐隐渐现时间
                         .setHasStroke(true) //是否有描边
                         .setBlurStroke(true) //是否模糊描边
                         .setStrokeWidth(3) //描边宽度
                         .setStrokeColor(Color.MAGENTA) //描边颜色
                         .setReappearTime(3000) // 设置跑马灯再次出现的间隔
                         .setStrokeAlpha(70)); //描边透明度

6. Half-Screen / Full-Screen Switching

The SDK does not provide a direct interface for half-screen/full-screen switching, but we have implemented this functionality in the Demo. The basic principle is to set the width and height of PolyvVideoView and PolyvPlayerMediaController to match_parent, then change the landscape/portrait status of Activity, and finally set the width and height of the common parent layout to adapt to landscape/portrait mode, thereby achieving half-screen/full-screen switching. The following example code is from the demo:

  1. Layout implementation:
<根布局...>
    <!--控制parent_view的高度-->
    <RelativeLayout
        android:id="@+id/parent_view"
        android:layout_width="match_parent"
        android:layout_height="300dp">

        <!--让 PolyvVideoView 和PolyvMediaPlayer 宽高跟随父布局-->
        <com.easefun.polyvsdk.video.PolyvVideoView
            android:id="@+id/polyv_video_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <com.shawn.testsdk.PolyvMediaPlayer
            android:id="@+id/media_player"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
        <其他.../>
    </RelativeLayout>
    
    <其他.../>
</根布局...>
  1. Set the configChanges property of Activity in AndroidManifest.xml:
//...AndroidManifest.xml
<activity
     android:name="com.easefun.polyvsdk.activity.PolyvPlayerActivity"
     android:configChanges="orientation|screenSize|keyboardHidden"
     ...>
    ...
</activity>
  1. Change the width and height properties of parent_view to achieve half-screen/full-screen switching:
  • Switch to full screen
//...PolyvPlayerMediaController.java
public void changeToLandscape() {
    PolyvScreenUtils.setLandscape(videoActivity);
    //初始为横屏时,状态栏需要隐藏
    PolyvScreenUtils.hideStatusBar(videoActivity);
    //初始为横屏时,导航栏需要隐藏
    PolyvScreenUtils.hideNavigationBar(videoActivity);
    //初始为横屏时,控制栏的宽高需要设置
    initLandScapeWH();
}

private void initLandScapeWH() {
    ViewGroup.LayoutParams vlp = parentView.getLayoutParams();
    vlp.width = ViewGroup.LayoutParams.MATCH_PARENT;
    vlp.height = ViewGroup.LayoutParams.MATCH_PARENT;
    ...
}

PolyvScreenUtils is a utility class defined in the Demo. Here, it mainly sets Activity to landscape mode.

  • Switch to half screen
//...polyvPlayerActivity
protected void onCreate(Bundle saveInstanceState){
    ...
    PolyvScreenUtils.generateHeight16_9(this);//记录高度
}
//...PolyvPlayerMediaController.java
public void changeToPortrait() {
    PolyvScreenUtils.setPortrait(videoActivity);
    initPortraitWH();
}

private void initPortraitWH() {
    ViewGroup.LayoutParams vlp = parentView.getLayoutParams();
    vlp.width = ViewGroup.LayoutParams.MATCH_PARENT;
    vlp.height = PolyvScreenUtils.getHeight16_9();
    ...
}
联系客服,在线咨询