Skip to content

嵌入其他程序

本节介绍 mpv 的 libmpv 嵌入接口。

libmpv 基础

头文件

c
#include <mpv/client.h>

基本用法

c
// 创建 mpv 实例
mpv_handle *ctx = mpv_create();

// 初始化
mpv_initialize(ctx);

// 播放视频
mpv_command(ctx, (const char*[]){"loadfile", "video.mp4", NULL});

// 事件循环
while (1) {
    mpv_event *event = mpv_wait_event(ctx, 1000);
    if (event->event_id == MPV_EVENT_SHUTDOWN)
        break;
}

// 清理
mpv_terminate_destroy(ctx);

属性操作

获取属性

c
// 获取属性
int64_t volume;
mpv_get_property(ctx, "volume", MPV_FORMAT_INT64, &volume);

// 获取字符串属性
char *title;
mpv_get_property(ctx, "media-title", MPV_FORMAT_STRING, &title);

设置属性

c
// 设置属性
int64_t volume = 80;
mpv_set_property(ctx, "volume", MPV_FORMAT_INT64, &volume);

// 设置字符串属性
mpv_set_property_string(ctx, "video-aspect", "16:9");

命令执行

执行命令

c
// 执行命令
mpv_command(ctx, (const char*[]){"seek", "10", NULL});

// 播放控制
mpv_command(ctx, (const char*[]){"set_property", "pause", "yes", NULL});

命令参数

c
// 带参数的命令
const char *args[] = {"loadfile", "video.mp4", NULL};
mpv_command(ctx, args);

事件处理

事件监听

c
// 事件循环
while (1) {
    mpv_event *event = mpv_wait_event(ctx, 1000);
    
    switch (event->event_id) {
        case MPV_EVENT_FILE_LOADED:
            printf("File loaded\n");
            break;
        case MPV_EVENT_END_FILE:
            printf("Playback ended\n");
            break;
        case MPV_EVENT_SHUTDOWN:
            goto done;
    }
}
done:

事件类型

c
// 常用事件
MPV_EVENT_FILE_LOADED
MPV_EVENT_END_FILE
MPV_EVENT_SHUTDOWN
MPV_EVENT_LOG_MESSAGE

日志处理

日志监听

c
// 设置日志级别
mpv_request_log_messages(ctx, "info");

// 日志事件处理
while (1) {
    mpv_event *event = mpv_wait_event(ctx, 1000);
    
    if (event->event_id == MPV_EVENT_LOG_MESSAGE) {
        mpv_event_log_message *msg = event->data;
        printf("[%s] %s", msg->prefix, msg->text);
    }
}

编译和链接

编译选项

bash
# 编译
gcc -o player player.c -lmpv

# 链接
gcc -o player player.c $(pkg-config --cflags --libs mpv)

CMake 配置

cmake
find_package(PkgConfig)
pkg_check_modules(MPV REQUIRED mpv)

add_executable(player player.c)
target_link_libraries(player ${MPV_LIBRARIES})
target_include_directories(player PRIVATE ${MPV_INCLUDE_DIRS})

示例代码

简单播放器

c
#include <mpv/client.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
    mpv_handle *ctx = mpv_create();
    mpv_initialize(ctx);
    
    // 播放视频
    mpv_command(ctx, (const char*[]){"loadfile", argv[1], NULL});
    
    // 事件循环
    while (1) {
        mpv_event *event = mpv_wait_event(ctx, 1000);
        if (event->event_id == MPV_EVENT_SHUTDOWN)
            break;
    }
    
    mpv_terminate_destroy(ctx);
    return 0;
}

调试

调试信息

c
// 设置日志级别
mpv_request_log_messages(ctx, "debug");

// 错误处理
int result = mpv_command(ctx, args);
if (result < 0) {
    printf("Error: %s\n", mpv_error_string(result));
}

下一步