ohos_ijkplayer:基于 OpenHarmony 的视频播放器项目

用户可用于在OpenHarmony环境下实现视频播放功能,支持视频源设置、播放控制、倍速播放、硬解码、视频录制等,基于FFmpeg,提供丰富的监听接口和配置选项。

Branch6Tags32
FilesLast commitLast update
1 year ago
10 months ago
5 months ago
3 years ago
4 months ago
2 years ago
3 years ago
3 years ago
2 years ago
5 months ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
7 months ago
1 year ago
4 months ago
4 months ago
1 year ago
3 years ago
9 months ago
3 years ago
5 months ago
5 months ago
2 years ago
2 years ago

ijkplayer

This project is based on ijkplayer.

Introduction

ijkplayer is a FFmpeg-based video player for OpenHarmony. It supports video playback, audio playback, variable-speed playback, hardware decoding, video recording, screenshots, and live streaming via HLS/RTSP/RTMP.

Preview

Installation

ohpm install @ohos/ijkplayer

For more information about setting up the OpenHarmony ohpm environment, see How to install an OpenHarmony ohpm package.

Constraints

Compatibility

Verified on the following configurations:

  • DevEco Studio: NEXT Beta1-5.0.3.806, SDK: API12 Release(5.0.0.66), ROM: OpenHarmony-5.0.0.71;
  • DevEco Studio NEXT 5.0(5.0.3.427), SDK: API12, ROM: OpenHarmony-5.0.0.71;

Listening for audio interrupt events requires device system version API 22 or above.

Setting volume requires SDK API 12 or above.

Hardware decoder buffer mode support for 10-bit video requires OpenHarmony API 22 or above.

Permissions

The following permissions must be declared in module.json5 depending on the features used:

Permission Description Required
ohos.permission.INTERNET Play network video streams (HTTP/RTSP/HLS/RTMP, etc.) Yes
ohos.permission.WRITE_IMAGEVIDEO Save recorded video or screenshots to the album Only when using recording/screenshot
// module.json5 example
"requestPermissions": [
  {
    "name": "ohos.permission.INTERNET",
    "reason": "$string:NET_REQUEST_PERMISSION"
  },
  {
    "name": "ohos.permission.WRITE_IMAGEVIDEO",
    "reason": "$string:IMAGEVIDEO_REQUEST_PERMISSION",
    "usedScene": {
      "when": "always"
    }
  }
]

Quick Start

The following example shows the minimal flow to play a network video: import → configure XComponent → initialize player → play.

id: The ID is the unique identifier of the component and is set by the user.

type: Use SURFACE, currently only SURFACE is supported.

libraryname: The name of the dynamic library is ijkplayer_napi.

Pure audio playback can work without using Xcomponent.

For specific usage of Xcomponent, refer to the official documentation: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ts-basic-components-xcomponent#xcomponent10

Step 1: Configure XComponent in your page

import { IjkMediaPlayer, OnPreparedListener, OnErrorListener } from "@ohos/ijkplayer";

@Entry
@Component
struct VideoPage {
  @State aspRatio: number = 16 / 9;
  private mContext: object | undefined = undefined;
  private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  private videoUrl: string = "https://example.com/sample.mp4";

  build() {
    Column() {
      // Step 1: Bind XComponent to the player
      XComponent({
        id: 'xcomponentId',
        type: XComponentType.SURFACE,
        libraryname: 'ijkplayer_napi'
      })
        .onLoad((context) => {
          this.mContext = context;
          this.startPlay();
        })
        .onDestroy(() => {
          this.mIjkMediaPlayer.release();
        })
        .width('100%')
        .aspectRatio(this.aspRatio)
    }
  }

  startPlay(): void {
    // Step 2: Initialize the player
    this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
    this.mIjkMediaPlayer.native_setup();

    // Step 3: Register callbacks
    let onPrepared: OnPreparedListener = {
      onPrepared() {
        console.info("Video ready, starting playback");
      }
    };
    this.mIjkMediaPlayer.setOnPreparedListener(onPrepared);

    let onError: OnErrorListener = {
      onError(what: number, extra: number) {
        console.error(`Playback error: what=${what}, extra=${extra}`);
      }
    };
    this.mIjkMediaPlayer.setOnErrorListener(onError);
    this.mIjkMediaPlayer.setMessageListener();

    // Step 4: Set data source and begin loading
    this.mIjkMediaPlayer.setDataSource(this.videoUrl);
    this.mIjkMediaPlayer.prepareAsync();
    this.mIjkMediaPlayer.start();
  }
}

Usage

Currently supported streaming protocols : HTTP/HTTPS,RTSP,HLS,RTMP,HTTP-FLV,FILE.

Initialization

Both singleton and multi-instance modes are supported:

import { IjkMediaPlayer } from "@ohos/ijkplayer";

// Singleton (shared global instance)
const mIjkMediaPlayer = IjkMediaPlayer.getInstance();

// Multi-instance (independent instance per player)
const mIjkMediaPlayer = new IjkMediaPlayer();

Typical initialization flow:

// Bind to XComponent (required for video; use setAudioId for audio-only)
mIjkMediaPlayer.setContext(this.mContext, "xcomponentId");
// Initialize internal player state
mIjkMediaPlayer.native_setup();
// Set the video source
mIjkMediaPlayer.setDataSource(url);
// Optional: set HTTP request headers (e.g. for authentication or User-Agent)
const headers = new Map<string, string>([
  ["user_agent", "Mozilla/5.0 BiliDroid/7.30.0 (bbcallen@gmail.com)"],
  ["referer", "https://www.bilibili.com"],
]);
mIjkMediaPlayer.setDataSourceHeader(headers);
// After registering callbacks, call these two methods to start loading and playback
mIjkMediaPlayer.setMessageListener();
mIjkMediaPlayer.prepareAsync();
mIjkMediaPlayer.start();

Playback Control

mIjkMediaPlayer.pause();              // Pause
mIjkMediaPlayer.start();             // Resume
mIjkMediaPlayer.stop();              // Stop
mIjkMediaPlayer.reset();             // Reset (allows re-setting a data source)
mIjkMediaPlayer.release();           // Release resources (call on page destroy)
mIjkMediaPlayer.seekTo("30000");     // Seek to position in milliseconds

Getting Playback Progress

Poll getCurrentPosition() on a timer to update a progress bar:

const timer = setInterval(() => {
  const currentMs: number = mIjkMediaPlayer.getCurrentPosition();
  const totalMs: number = mIjkMediaPlayer.getDuration();
  const progress = totalMs > 0 ? (currentMs / totalMs) * 100 : 0;
  console.info(`Progress: ${currentMs}ms / ${totalMs}ms (${progress.toFixed(1)}%)`);
}, 500);

// Clear the timer when done
clearInterval(timer);

Variable-Speed Playback

// Enable variable-speed (requires soundtouch library)
mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
mIjkMediaPlayer.setSpeed("2f");    // Set 2x speed
mIjkMediaPlayer.getSpeed();       // Get current speed value

Note: Variable-speed playback is not available for videos without audio tracks.

Volume and Screen Wake Lock

mIjkMediaPlayer.setVolume("1.0", "1.0");          // Set left/right channel volume (0.0-1.0)
mIjkMediaPlayer.setScreenOnWhilePlaying(true);    // Keep screen on during playback

Loop Playback

mIjkMediaPlayer.setLoopCount(true);  // Enable looping
mIjkMediaPlayer.isLooping();         // Check if looping is enabled

Advanced Options

Configure player behavior with setOption. Common parameters:

// Accurate seek: jump to exact position instead of nearest keyframe
mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
// Read buffer size in bytes (recommended: 100 KB)
mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "102400");
// Max buffered duration in ms - prevents latency accumulation in live streams
mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
// Unlimited input buffering (suitable for live/long-running streams)
mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
// Timeout in microseconds for weak network environments
mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");

setOption / setOptionLong Parameter Reference

All parameters must be set before calling prepareAsync().

OPT_CATEGORY_PLAYER ("4") — Player-level parameters

key Value type Default Description
enable-accurate-seek integer 0 Accurate seek: 1=seek to exact timestamp, 0=seek to nearest keyframe (faster).
soundtouch integer 0 Enable soundtouch pitch correction for variable-speed playback. Must be set before setSpeed().
mediacodec-all-videos integer 0 Enable hardware decoding (H.264/H.265, etc.).
overlay-format integer 808596553 Output pixel format: 842094158=NV12, 808596553=I420.
max-buffer-size integer 15728640 Max read-ahead buffer size in bytes. Recommended for VOD: 102400.
min-frames integer 50000 Minimum buffered frames before playback starts. Lower reduces startup latency; higher reduces stuttering.
max_cached_duration integer 0 Max buffer duration in milliseconds. Used to control live stream latency, e.g. "3000".
infbuf integer 0 Unlimited buffer mode, ignores max_cached_duration. Suitable for VOD or latency-insensitive live streams.
packet-buffering integer 1 Packet buffering mode: 0=disabled (more real-time), 1=enabled.
framedrop integer 0 Frame drop threshold (frames). Drops frames when video lags audio beyond this value. Recommended for live: "5". 0=no drop.
start-on-prepared integer 1 1=auto-start after prepared callback; 0=manual start() required.
loop integer 1 Loop count: 0=infinite loop, 1=no loop (normally set via setLoopCount()).

OPT_CATEGORY_FORMAT ("1") — Format/protocol-level parameters

key Value type Default Description
timeout integer 0 I/O read timeout in microseconds. 10000000=10 seconds.
connect_timeout integer 0 TCP connection timeout in microseconds.
listen_timeout integer 0 RTSP/TCP server listen timeout in microseconds.
addrinfo_timeout integer 0 DNS resolution timeout in microseconds.
dns_cache_timeout integer 600000000 DNS cache TTL in microseconds. -1=cache forever, 0=no cache.
rtsp_transport string udp RTSP transport protocol: tcp (recommended, stable) / udp / udp_multicast.
allowed_extensions string — Allowed file extensions. "ALL" disables filtering.
fetch_first string — HLS startup latency optimization: "on"=enable.
headers string — Custom HTTP request headers (normally set via setDataSourceHeader()).

OPT_CATEGORY_CODEC ("2") — Codec-level parameters

key Value type Default Description
skip_loop_filter integer 0 Skip loop filter deblocking: 0=full filter, 48=skip B/P frames (reduces CPU usage, slight quality loss).

Note: setOption sets string-type parameters; setOptionLong sets integer-type parameters (value is still passed as a string, e.g. "1"). Both must be called before prepareAsync().

Audio Focus Monitoring

import { InterruptEvent, InterruptHintType } from '@ohos/ijkplayer';
import { Callback } from '@ohos.base';

const audioInterruptCallback: Callback<InterruptEvent> = (event) => {
  if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
    mIjkMediaPlayer.pause();
  } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
    mIjkMediaPlayer.start();
  } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
    mIjkMediaPlayer.stop();
  }
};

// Subscribe to audio interrupt events
mIjkMediaPlayer.on('audioInterrupt', audioInterruptCallback);
// Unsubscribe
mIjkMediaPlayer.off('audioInterrupt');

Audio Device Change Monitoring

import { InterruptEvent, DeviceChangeReason } from '@ohos/ijkplayer';
import { Callback } from '@ohos.base';

const deviceChangeCallback: Callback<InterruptEvent> = (event) => {
  if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) {
    // New device connected - resume playback if desired
  } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) {
    // Device disconnected - pause playback
    mIjkMediaPlayer.pause();
  }
};

// Subscribe to device change events
mIjkMediaPlayer.on('deviceChange', deviceChangeCallback);
// Unsubscribe
mIjkMediaPlayer.off('deviceChange');

Hardware Decoding

// Enable hardware decoding for H.264 and H.265
mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-all-videos", "1");
// Set output pixel format: NV12(842094158) or I420(808596553)
mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "overlay-format", "842094158");

Note: Hardware decoder buffer mode support for 10-bit video requires OpenHarmony API 22 or above.

Adaptive Playback of Resolution-Changing Videos

Supports adaptive playback of videos whose resolution changes during playback. Both software and hardware decoding are supported. No additional APIs are required.

import { OnVideoSizeChangedListener } from "@ohos/ijkplayer";

const sizeListener: OnVideoSizeChangedListener = {
  onVideoSizeChanged(width: number, height: number, sar_num: number, sar_den: number) {
    console.info(`Resolution changed: ${width}x${height}, sar=${sar_num}/${sar_den}`);
    // Update XComponent or container layout to avoid stretching
  }
};
mIjkMediaPlayer.setOnVideoSizeChangedListener(sizeListener);

When the source resolution changes, onVideoSizeChanged may fire multiple times; getVideoWidth() and getVideoHeight() return the currently active dimensions.

Track Selection

Retrieve media info, then switch audio or subtitle tracks by track index:

// Get media stream information (includes audio/video track list)
const mediaInfo: object = mIjkMediaPlayer.getMediaInfo();
console.info(`Media info: ${JSON.stringify(mediaInfo)}`);

// Switch to a specific track (trackId obtained from getMediaInfo)
mIjkMediaPlayer.selectTrack("1");    // Select track ID 1

// Deselect the current track
mIjkMediaPlayer.deselectTrack("1");

Video Recording

Note: Saving recordings to the album requires the ohos.permission.WRITE_IMAGEVIDEO permission.

// Start recording
const savePath: string = getContext(this).cacheDir + "/record.mp4";
mIjkMediaPlayer.setRecordDefaultFrameRate("30", false); // Fallback frame rate when stream FPS is unavailable
const started: boolean = mIjkMediaPlayer.startRecord(savePath);

// Check recording status
const isRecording: boolean = mIjkMediaPlayer.isRecord();

// Stop recording and save to album
mIjkMediaPlayer.stopRecord().then((result) => {
  if (result) {
    console.info("Recording stopped, saved to: " + savePath);
  }
});

Screenshot

Note: Saving screenshots to the album requires the ohos.permission.WRITE_IMAGEVIDEO permission.

const screenshotPath: string = getContext(this).cacheDir + "/screen.jpg";
mIjkMediaPlayer.screenshot(screenshotPath).then((result) => {
  if (result) {
    console.info("Screenshot saved to: " + screenshotPath);
  }
});

Timed Text Callback

import { OnTimedTextListener } from "@ohos/ijkplayer";

// Register timed text callback (must be set before setMessageListener)
const timedTextListener: OnTimedTextListener = {
  onTimedText(text: string) {
    console.info("Subtitle: " + text);
  }
};
mIjkMediaPlayer.setOnTimedTextListener(timedTextListener);

Note: setOnTimedTextListener must be called before setMessageListener(). The callback is triggered via MEDIA_TIMED_TEXT (value 99) events.

HLS Start Optimization

// Enable HLS startup latency optimization (disabled by default)
mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "fetch_first", "on");

Async Stop and Release

// Async variants for performance-sensitive scenarios (e.g. fast source switching)
mIjkMediaPlayer.stopAsync().then((result) => {
  console.info("Async stop completed");
});
mIjkMediaPlayer.releaseAsync().then((result) => {
  console.info("Async release completed");
});

API Reference

API

Name Parameters Return Description
setContext context: object, id?: string void Set XComponent context and optional id. Required for video playback.
setAudioId id: string void Set audio object ID. Use instead of setContext for audio-only playback.
setDebug open: boolean void Enable or disable debug logging.
native_setup mode?: VideoCodecMode void Initialize the configuration and specify the video decoder decoding method, default is buffer mode, must be called before configuring the player
setDataSource url: string void Set the video source URL (HTTP/HTTPS/RTSP/RTMP/HLS supported).
setDataSourceHeader headers: Map<string, string> void Set HTTP request headers for the video source.
setOption category: string, key: string, value: string void Set a string-type playback parameter (call before playback starts).
setOptionLong category: string, key: string, value: string void Set an integer-type playback parameter (call before playback starts).
prepareAsync - void Asynchronously load the video resource.
start - void Start or resume playback.
pause - void Pause playback.
stop - void Stop playback.
stopAsync - Promise<boolean> Stop playback asynchronously.
reset - void Reset the player state (allows re-setting the data source).
release - void Release all player resources.
releaseAsync - Promise<boolean> Release resources asynchronously.
seekTo msec: string void Seek to the specified position in milliseconds.
isPlaying - boolean Returns whether the player is currently playing.
getDuration - number Returns the total video duration in milliseconds.
getCurrentPosition - number Returns the current playback position in milliseconds.
getVideoWidth - number Returns the video width in pixels.
getVideoHeight - number Returns the video height in pixels.
getVideoSarNum - number Returns the numerator of the video sample aspect ratio.
getVideoSarDen - number Returns the denominator of the video sample aspect ratio.
getAudioSessionId - number Returns the audio session ID.
setSpeed speed: string void Set the playback speed, e.g. "1f", "2f" (requires soundtouch option enabled).
getSpeed - number Returns the currently configured playback speed.
setVolume leftVolume: string, rightVolume: string void Set left/right channel volume. Requires SDK API 12 or above.
setScreenOnWhilePlaying on: boolean void Keep the screen on during playback.
setLoopCount looping: boolean void Enable or disable loop playback.
isLooping - boolean Returns whether loop playback is enabled.
selectTrack track: string void Select the specified track.
deselectTrack track: string void Deselect the specified track.
getMediaInfo - object Returns media stream information (including audio/video track list).
setMessageListener - void Register event listeners into the native layer. Must be called before registering callbacks.
setOnPreparedListener listener: OnPreparedListener void Fired when the video is ready to play.
setOnVideoSizeChangedListener listener: OnVideoSizeChangedListener void Fired when video dimensions become available.
setOnCompletionListener listener: OnCompletionListener void Fired when playback completes.
setOnInfoListener listener: OnInfoListener void Fired on internal player state changes (see OnInfoListener callback values below).
setOnErrorListener listener: OnErrorListener void Fired on playback errors.
setOnBufferingUpdateListener listener: OnBufferingUpdateListener void Fired on buffering progress updates; percent is the buffer percentage.
setOnSeekCompleteListener listener: OnSeekCompleteListener void Fired when a seek operation completes.
setOnTimedTextListener listener: OnTimedTextListener void Fired on timed text / subtitle events. onTimedText(text: string) receives the subtitle content.
on type: 'audioInterrupt', callback: Callback<InterruptEvent> void Subscribe to audio interrupt events. Requires API 22 or above.
on type: 'deviceChange', callback: Callback<InterruptEvent> void Subscribe to audio device connect/disconnect events.
off type: 'audioInterrupt' void Unsubscribe from audio interrupt events.
off type: 'deviceChange' void Unsubscribe from audio device change events.
setRecordDefaultFrameRate frameRate: string, isPriority: boolean boolean Set default recording frame rate. When isPriority is true, only applies if stream FPS is unavailable.
startRecord saveFilePath: string boolean Start recording. Returns whether it was successful.
isRecord - boolean Returns whether recording is in progress.
stopRecord - Promise<boolean> Stop recording asynchronously. Returns whether successful.
screenshot saveFilePath: string Promise<boolean> Capture and save the current frame to the specified path.
getVideoDecoder - number Returns the current video decoder type; 1=software (AVCodec), 2=hardware (MediaCodec).
getVideoOutputFramesPerSecond - number Returns the video output frame rate (fps).
getVideoDecodeFramesPerSecond - number Returns the video decode frame rate (fps).
getVideoCachedDuration - number Returns the video buffer duration in milliseconds.
getAudioCachedDuration - number Returns the audio buffer duration in milliseconds.
getVideoCachedBytes - number Returns the video buffer size in bytes.
getAudioCachedBytes - number Returns the audio buffer size in bytes.
getVideoCachedPackets - number Returns the number of buffered video packets.
getAudioCachedPackets - number Returns the number of buffered audio packets.
getAsyncStatisticBufBackwards - number Returns the size of the async buffer for backward direction.
getAsyncStatisticBufForwards - number Returns the size of the async buffer for forward direction.
getAsyncStatisticBufCapacity - number Returns the capacity of the async buffer.
getTrafficStatisticByteCount - number Returns the total downloaded traffic in bytes.
getCacheStatisticPhysicalPos - number Returns the physical position of the cache.
getCacheStatisticFileForwards - number Returns the forward position of the cache.
getCacheStatisticFilePos - number Returns the current position of the cache.
getCacheStatisticCountBytes - number Returns the number of bytes cached.
getBitRate - number Returns the current playback bit rate (bit/s).
getTcpSpeed - number Returns the current TCP download speed (byte/s).
getSeekLoadDuration - number Returns the load duration of the most recent seek operation (ms).
getDropFrameRate - number Returns the current frame drop rate.
getFileSize - number Returns the total media file size in bytes; returns 0 for live streams.
setCacheShare share: string void Enable or disable cache data sharing; "1"=enable, "0"=disable.

onErrorListener Callback Values

The what values in onError(what: number, extra: number):

what Constant Description
1 MEDIA_ERROR_UNKNOWN Unknown error
100 MEDIA_ERROR_SERVER_DIED Server dead
200 MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK Progressive playback is not supported
-1004 MEDIA_ERROR_IO IO Error
-1007 MEDIA_ERROR_MALFORMED Format error
-1010 MEDIA_ERROR_UNSUPPORTED Not supported
-110 MEDIA_ERROR_TIMED_OUT Timeout
-10000 MEDIA_ERROR_IJK_PLAYER Player error

OnInfoListener Callback Values

The what values in onInfo(what: number, extra: number):

what Constant Description
3 MEDIA_INFO_VIDEO_RENDERING_START Video rendering started (first frame output)
701 MEDIA_INFO_BUFFERING_START Buffering started
702 MEDIA_INFO_BUFFERING_END Buffering ended
10001 MEDIA_INFO_VIDEO_ROTATION_CHANGED Video rotation changed (extra = rotation angle in degrees)
10002 MEDIA_INFO_AUDIO_RENDERING_START Audio rendering started
10003 MEDIA_INFO_AUDIO_DECODED_START Audio decoding started
10004 MEDIA_INFO_VIDEO_DECODED_START Video decoding started
10005 MEDIA_INFO_OPEN_INPUT Opening input/source started (begin connecting or reading media input)
10006 MEDIA_INFO_FIND_STREAM_INFO Stream information found and parsed (track/codec info available)
10007 MEDIA_INFO_COMPONENT_OPEN Decoder/renderer component opened (decoder or renderer initialized)
10008 MEDIA_INFO_VIDEO_SEEK_RENDERING_START Video seek rendering started
10009 MEDIA_INFO_AUDIO_SEEK_RENDERING_START Audio seek rendering started
10100 MEDIA_INFO_MEDIA_ACCURATE_SEEK_COMPLETE Accurate seek complete (extra/arg may include seek position)

InterruptEvent Parameters

Field Type Required Description
forceType InterruptForceType Yes Whether the interruption is forced by the system (INTERRUPT_FORCE) or handled by the app (INTERRUPT_SHARE).
hintType InterruptHint Yes Interrupt type hint. See enum table below.
reason DeviceChangeReason No Device change reason. Only present in deviceChange events.

InterruptForceType Enum

Name Value Description
INTERRUPT_FORCE 0 Interruption is performed by the system.
INTERRUPT_SHARE 1 Interruption is handled by the application.

InterruptHint Enum

Name Value Description
INTERRUPT_HINT_NONE 0 No hint.
INTERRUPT_HINT_RESUME 1 Resume playback.
INTERRUPT_HINT_PAUSE 2 Pause playback.
INTERRUPT_HINT_STOP 3 Stop playback.
INTERRUPT_HINT_DUCK 4 Lower volume (do not stop).
INTERRUPT_HINT_UNDUCK 5 Restore normal volume.

DeviceChangeReason Enum

名称 值 说明
REASON_UNKNOWN 0 Unknown
REASON_NEW_DEVICE_AVAILABLE 1 New Device available.
REASON_OLD_DEVICE_UNAVAILABLE 2 Old Device unavailable. Applications should consider to pause the audio playback when this reason isreported
REASON_OVERRODE 3 Device is overrode by user or system

VideoCodecMode Enum

名称 值 说明
BUFFER 0 The video decoder uses buffer mode for decoding
SURFACE 1 The video decoder uses surface mode for decoding

OnTimedTextListener Callback

onTimedText(text: string) is triggered during playback of videos with subtitle tracks. text contains the subtitle string.

MessageType Constants

The MessageType class defines internal player message types. You can import and reference them directly:

import { MessageType } from "@ohos/ijkplayer";
Constant Value Description
MEDIA_PREPARED 1 Video is ready to play
MEDIA_PLAYBACK_COMPLETE 2 Playback completed
MEDIA_BUFFERING_UPDATE 3 Buffering progress update
MEDIA_SEEK_COMPLETE 4 Seek operation completed
MEDIA_SET_VIDEO_SIZE 5 Video dimensions available
MEDIA_TIMED_TEXT 99 Timed text / subtitle event
MEDIA_ERROR 100 Playback error
MEDIA_INFO 200 Internal player info event
MEDIA_AUDIO_INTERRUPT 201 Audio interrupt event
MEDIA_AUDIO_DEVICE_CHANGE 202 Audio device change event
MEDIA_SET_VIDEO_SAR 10001 Video aspect ratio updated

PropertiesType Constants

The PropertiesType class defines internal player diagnostic property constants, used with the statistics/diagnostic API methods.

import { PropertiesType } from "@ohos/ijkplayer";

Float property constants

Constant Value Description
PROP_FLOAT_VIDEO_DECODE_FRAMES_PER_SECOND "10001" Video decode frame rate
PROP_FLOAT_VIDEO_OUTPUT_FRAMES_PER_SECOND "10002" Video output frame rate
FFP_PROP_FLOAT_PLAYBACK_RATE "10003" Playback speed (used by setSpeed() / getSpeed())
FFP_PROP_FLOAT_DROP_FRAME_RATE "10007" Drop frame rate

Decoder type constants (used with getVideoDecoder() return value)

Constant Value Description
FFP_PROPV_DECODER_UNKNOWN "0" Unknown decoder
FFP_PROPV_DECODER_AVCODEC "1" Software decoder (FFmpeg AVCodec)
FFP_PROPV_DECODER_MEDIACODEC "2" Hardware decoder (MediaCodec)

Cache statistics constants (integer properties)

Constant Value Description
FFP_PROP_INT64_VIDEO_CACHED_DURATION "20005" Video buffer duration (ms)
FFP_PROP_INT64_AUDIO_CACHED_DURATION "20006" Audio buffer duration (ms)
FFP_PROP_INT64_VIDEO_CACHED_BYTES "20007" Video buffer size (bytes)
FFP_PROP_INT64_AUDIO_CACHED_BYTES "20008" Audio buffer size (bytes)
FFP_PROP_INT64_VIDEO_CACHED_PACKETS "20009" Buffered video packet count
FFP_PROP_INT64_AUDIO_CACHED_PACKETS "20010" Buffered audio packet count
FFP_PROP_INT64_BIT_RATE "20100" Current bit rate (bit/s)
FFP_PROP_INT64_TCP_SPEED "20200" TCP download speed (byte/s)
FFP_PROP_INT64_LATEST_SEEK_LOAD_DURATION "20300" Most recent seek load duration (ms)
FFP_PROP_INT64_TRAFFIC_STATISTIC_BYTE_COUNT "20204" Total downloaded traffic (bytes)
FFP_PROP_INT64_LOGICAL_FILE_SIZE "20209" Total media file size (bytes)
FFP_PROP_INT64_SHARE_CACHE_DATA "20210" Cache data sharing flag (used by setCacheShare())

Obfuscation

  • For an introduction to code obfuscation, see ArkTS Source Obfuscation.
  • To exclude the ijkplayer library from obfuscation, add the following to your obfuscation-rules.txt:
-keep
./oh_modules/@ohos/ijkplayer

Notes

Lifecycle management (required): You must implement full lifecycle state management for the player instance, otherwise resource leaks or crashes will occur. Refer to the IjkplayerMapManager implementation in the Demo.

Cross-page usage: In multi-page scenarios (e.g. a list page and a detail page sharing the same player), correctly transfer and restore the XComponent binding during page navigation to avoid a black screen. See the Navigation example and non-Navigation example.

Multi-instance callback isolation: When using new IjkMediaPlayer(), callbacks for each instance are independent. Ensure setOnXxxListener is called separately for each instance to avoid callbacks being overwritten.

Screen rotation black screen: When the screen rotates and the XComponent is destroyed and recreated, call setContext again in the onLoad callback and restore playback based on the current state.

Adaptive playback of resolution-changing videos: When the source resolution changes, onVideoSizeChanged may fire multiple times. Update the XComponent or container layout to avoid stretching or black bars. See IjkVideoDynamicResolutionPage.ets.

Building from Source

The following steps are only needed if you intend to build from source. Regular users should install via ohpm install @ohos/ijkplayer.

Build Third-Party Dependencies

  1. FFmpeg (version ff4.0--ijk0.8.8--20210426--001): FFmpeg source - follow the FFmpeg-ff4.0 build guide. Rename the output folder from FFmpeg-ff4.0 to ffmpeg.

  2. soundtouch (version ijk-r0.1.2-dev): soundtouch source - copy doc/soundtouch-ijk to the thirdparty directory, then run ./build.sh soundtouch-ijk from the lycium directory.

  3. libyuv (version ijk-r0.2.1-dev): libyuv source - copy doc/libyuv-ijk to the thirdparty directory, then run ./build.sh libyuv-ijk from the lycium directory.

  4. openh264 (version openh264-2.4.1): openh264 source - refer to the openh264 build scripts. Output goes to lycium/usr/openh264.

  5. Copy the ffmpeg folder to ijkplayer/src/main/cpp/third_party/ffmpeg.

  6. Copy the openssl-3.4.0 folder to ijkplayer/src/main/cpp/third_party, rename it to openssl, and rename the x86_64/lib64 subdirectory to x86_64/lib.

  7. Copy the soundtouch, yuv, and openh264 folders to ijkplayer/src/main/cpp/third_party, as shown below:

third_party directory structure

Build and Run in IDE

  1. Open the project in DevEco Studio, go to Tools -> SDK Manager -> OpenHarmony SDK, and download the native component for API version >= 9.
  2. Target board: RK3568. Download the latest ROM from OpenHarmony CI.
  3. Use git clone to download the source code. Do not download a zip from the web page.

Directory Structure

|---- ohos_ijkplayer
|     |---- entry/                   # Sample code
|     |---- ijkplayer/               # ijkplayer library
|           |---- cpp/               # Native module
|                 |---- ijkplayer/   # ijkplayer core logic
|                 |---- ijksdl/      # ijkplayer SDL adaptation layer
|                 |---- napi/        # NAPI interface wrappers
|                 |---- proxy/       # Proxy layer (bridges NAPI and ijkplayer)
|                 |---- third_party/ # Third-party deps (ffmpeg/yuv/soundtouch/openh264)
|                 |---- utils/       # Utilities
|           |---- ets/               # ArkTS interface module
|                 |---- callback/    # Player callback interface definitions
|                 |---- common/      # Constants and enums (MessageType, PropertiesType)
|                 |---- utils/       # Utilities (LogUtils)
|                 |---- IjkMediaPlayer.ets  # Core API exposed to consumers
|           |---- index.ets          # Library entry point, exports all public APIs
|     |---- README.md                # English documentation
|     |---- README_zh.md             # Chinese documentation

Contributing

If you find any issues while using this library, feel free to open an Issue or submit a PR.

License

This project is licensed under LGPLv2.1 or later.

Introduction

用户可用于在OpenHarmony环境下实现视频播放功能,支持视频源设置、播放控制、倍速播放、硬解码、视频录制等,基于FFmpeg,提供丰富的监听接口和配置选项。

Customize your domain