You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Azure Media Services v3中获取资产的平均观看时长

Azure Media Services 视频统计分析实现方案

核心实现思路

要获取平均观看时长、观看次数这类视频统计数据,结合Application Insights是高效可行的方案:前端通过媒体播放器采集播放关键事件(如播放启动、暂停、结束),后端借助TelemetryClient接收并上报这些事件到Application Insights,最后通过平台的日志查询功能聚合计算所需指标。

.NET 6 后端代码示例

1. 安装依赖包

先安装Application Insights SDK:

dotnet add package Microsoft.ApplicationInsights.AspNetCore

2. 配置Application Insights

在appsettings.json中添加连接配置:

{
  "ApplicationInsights": {
    "ConnectionString": "你的Application Insights连接字符串"
  }
}

3. 注册Telemetry服务

在Program.cs中完成服务注册:

var builder = WebApplication.CreateBuilder(args);

// 注入Application Insights服务
builder.Services.AddApplicationInsightsTelemetry();

var app = builder.Build();

app.Run();

4. 自定义播放事件上报接口

创建API控制器接收前端上报的播放事件:

using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/telemetry")]
public class VideoTelemetryController : ControllerBase
{
    private readonly TelemetryClient _telemetryClient;

    public VideoTelemetryController(TelemetryClient telemetryClient)
    {
        _telemetryClient = telemetryClient;
    }

    [HttpPost("play-event")]
    public IActionResult TrackPlayEvent([FromBody] VideoPlayEvent playEvent)
    {
        // 将播放事件上报至Application Insights
        _telemetryClient.TrackEvent("VideoPlayEvent", new Dictionary<string, string>
        {
            { "VideoId", playEvent.VideoId },
            { "UserId", playEvent.UserId },
            { "EventName", playEvent.EventName }
        }, new Dictionary<string, double>
        {
            { "Duration", playEvent.Duration }
        });

        return Ok();
    }
}

// 播放事件数据模型
public class VideoPlayEvent
{
    public string VideoId { get; set; }
    public string UserId { get; set; }
    public string EventName { get; set; } // 可选值:PlayStarted、PlayPaused、PlayCompleted
    public double Duration { get; set; } // 累计观看时长(单位:秒)
}

指标查询方法

在Application Insights的日志查询界面,使用Kusto查询语言计算目标指标:

1. 视频观看次数

customEvents
| where name == "VideoPlayEvent"
| where customDimensions.EventName == "PlayStarted"
| summarize WatchCount = count() by customDimensions.VideoId

2. 视频平均观看时长

customEvents
| where name == "VideoPlayEvent"
| where customDimensions.EventName == "PlayCompleted"
| summarize AvgWatchDuration = avg(customMeasurements.Duration) by customDimensions.VideoId

前端配合提示

前端可基于Azure Media Player监听播放生命周期事件,在用户触发播放启动、暂停、结束等操作时,调用上述后端接口上报事件数据。例如播放结束时,计算累计观看时长并同步上报。

内容的提问来源于stack exchange,提问作者Mario Lada Martínez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 04:18:20