前言:
本篇我们来介绍如何使用Facebook 的直播API(Facebook Live API)创建直播。
准备工作:
1、你首先得有个facebook账号;
2、创建facebook应用,填写应用审核信息,上线前还要提前做好API权限申请,如果你也需要在用户时间线、公共主页、小组都创建直播,那你可能需要提前申请Live Video API、Groups API、pages_manage_posts、pages_read_engagement、publish_video、publish_to_groups,但是要注意的一点是你创建的应用必须是商务应用才有这些直播权限可以申请,就在Facebook应用管理页面”应用审核“-》”权限和功能“申请;
3、你的应用需要集成facebook的账号授权SDK,用来拉起facebook账号的登录授权页面获得用户授权的,需要获取对用户facebook账号数据的操作权限,scope(权限范围)要请求pages_manage_posts、pages_read_engagement、publish_video、publish_to_groups,这里需要大家对OAuth2.0的流程有一定理解;
4、先调通用户授权流程获得具有直播API操作权限的token后即可调用Facebook Live 直播API或者你自己对Facebook直播API的后台封装。
直播API封装:
代码部分使用JAVA语言实现(代码只提供主流程代码)
先附上Facebook Live API的官方文档。
facebook账号中的直播间种类分为在你账号主页下、某个公共主页下或者某个小组下的直播间,从官方的API来看,创建这三种类型的直播接口是同一个,只需要告诉接口是去哪个主页或者哪个小组创建,用户主页下的只需要告诉接口user_id为”me“下创建就行,如下面官方API列表展示的那样:
调用该接口创建直播对象后就会返回一个可用的推流地址:
创建用户主页的直播,路径上的对象ID传“me”就行,但是公共主页和小组的page_id和group_id怎么得到呢?这需要单独查询用户账号下有权限的公共主页和小组的信息,下面我给出用JAVA封装的查询代码:
查询公共主页列表信息:
java">public Object queryFacebookPublicPages(String facebookToken) {Object result;log.info("[RtmpManageServiceImpl.queryFacebookPublicPages]enter service.");try {Map<String, String> header = new HashMap<>();String authorization = "Bearer " + facebookToken;header.put("Authorization", authorization);String url = "https://graph.facebook.com/v3.3/me/accounts";String resultStr = HttpUtils.get(url, header);log.info("[RtmpManageServiceImpl.queryFacebookPublicPages] result str:{}.", resultStr);JSONObject object = JSON.parseObject(resultStr);result = object;log.info("[RtmpManageServiceImpl.queryFacebookPublicPages]out service.");} catch (NorthException ex) {log.error("[RtmpManageServiceImpl.queryFacebookPublicPages] query facebook public pages failed! error msg:{}", ex.getErrorMsg());throw ex;} catch (Exception ex) {log.error("[RtmpManageServiceImpl.queryFacebookPublicPages]query facebook public pages failed! error msg:{}.", ex.getMessage());throw new NorthException(NorthErrorEnum.SERVER_INTERNAL_ERROR);}log.info("[RtmpManageServiceImpl.queryFacebookPublicPages]out service.");return result;}
返回值示例如下:
java">{"data": [{"access_token": "EAAP7H3sjRA0BADILG09JyW5Yyg16VZBTbZC1onVwolpeWFG9Uk4F3tckvnrlZCouJlJp8ON8IUEl3I31Rrm35pPxxjAZBn50aXEbxTOsg7ZBTuxQYje50ZBmy9MOAftVl9Kz3l5cBAZA0EMw53tTxUFfl6Vx1FRNJOzc1dIwRnQtZA7ZB8qfL9k2LJj0AJdZAUaSKzgcEvEELU0gZDZD","category": "广播与媒体制作公司","category_list": [{"id": "169056916123567","name": "广播与媒体制作公司"}],"name": "Deemoo-Live","id": "101999706123456", // 公共主页ID(page_id)"tasks": ["ADVERTISE","ANALYZE","CREATE_CONTENT","MESSAGING","MODERATE","MANAGE"]}],"paging": {"cursors": {"before": "MTAxOTk5NzA2MDkxMzgz","after": "MTAxOTk5NzA2MDkxMzgz"}}
}
查询用户小组列表信息:
java">public Object queryFacebookGroups(String facebookToken) {Object result;log.info("[RtmpManageServiceImpl.queryFacebookGroups]enter service.");try {Map<String, String> header = new HashMap<>();String authorization = "Bearer " + facebookToken;header.put("Authorization", authorization);String url = "https://graph.facebook.com/v3.3/me/groups";String resultStr = HttpUtils.get(url, header);log.info("[RtmpManageServiceImpl.queryFacebookGroups] result str:{}.", resultStr);JSONObject object = JSON.parseObject(resultStr);result = object;log.info("[RtmpManageServiceImpl.queryFacebookGroups]out service.");} catch (NorthException ex) {log.error("[RtmpManageServiceImpl.queryFacebookGroups] query facebook groups failed! error msg:{}", ex.getErrorMsg());throw ex;} catch (Exception ex) {log.error("[RtmpManageServiceImpl.queryFacebookGroups]query facebook groups failed! error msg:{}.", ex.getMessage());throw new NorthException(NorthErrorEnum.SERVER_INTERNAL_ERROR);}log.info("[RtmpManageServiceImpl.queryFacebookGroups]out service.");return result;}
返回值示例如下:
java">{"data": [{"name": "test-group","privacy": "OPEN","id": "507770147912345" // 小组ID(group_id)}],"paging": {"cursors": {"before": "QVFIUkd5U0xLRTEya3RUUzVZAV0wxWjNoam9FdVFwN3lTTV94YkM3UVVlQ0NFVlIwNlpibFdUdGM5cUNaVEFTMEp4bTJBSG1BemtXMnJnZATNUUEFVaXNLZAnVR","after": "QVFIUkd5U0xLRTEya3RUUzVZAV0wxWjNoam9FdVFwN3lTTV94YkM3UVVlQ0NFVlIwNlpibFdUdGM5cUNaVEFTMEp4bTJBSG1BemtXMnJnZATNUUEFVaXNLZAnVR"}}
}
然后就可以用JAVA封装创建直播对象并获得推流地址的方法实现:
java">public CreateLiveVideoVo createFacebookLiveVideo(CreateLiveVideoDto params, String userId) {CreateLiveVideoVo result = new CreateLiveVideoVo();log.info("[RtmpManageServiceImpl.createFacebookLiveVideo]enter service.");try {Date currentTime = DateUtils.getCurrentDateTime();String type = params.getType();String targetId = params.getTargetId();String status = params.getStatus();String facebookToken = params.getFacebookToken();String title = params.getTitle();String description = params.getDescription();Long startTime = params.getStartTime();String cover = params.getCover();// 封装请求参数 参数具体含义见官方文档Map<String, Object> data = new HashMap<>();if (startTime != null || cover != null) {Map<String, Object> eventParams = new HashMap<>();eventParams.put("start_time", params.getStartTime());eventParams.put("cover", params.getCover());data.put("event_params", eventParams);data.put("published", false);}data.put("title", title);data.put("description", description);data.put("access_token", facebookToken);data.put("status", status);if ("me".equals(targetId)) {if (params.getPrivacy() != null) {Map<String, Object> privacy = new HashMap<>();privacy.put("value", params.getPrivacy());data.put("privacy", privacy);}}JSONObject jsonObject = new JSONObject(data);String jsonStr = jsonObject.toString();String authorization = "Bearer " + facebookToken;String url = "https://graph.facebook.com/v3.3/" + targetId + "/live_videos";String resultStr = "";String contentType = "application/json;charset=utf-8";resultStr = HttpUtils.post(url, jsonStr, authorization, contentType, "");log.info("[RtmpManageServiceImpl.createFacebookLiveVideo] result str:{}.", resultStr);JSONObject object = JSON.parseObject(resultStr);String rtmpUrl = object.getString("secure_stream_url");// 推流地址信息String liveId = object.getString("id");result.setLiveId(liveId);result.setEventId(object.getString("event_id"));result.setSecureStreamUrl(rtmpUrl);log.info("[RtmpManageServiceImpl.createFacebookLiveVideo]out service.");} catch (NorthException ex) {throw ex;} catch (Exception ex) {log.error("[RtmpManageServiceImpl.createFacebookLiveVideo]create facebook live video info failed! error msg:{}.", ex.getMessage());throw new NorthException(NorthErrorEnum.SERVER_INTERNAL_ERROR);}log.info("[RtmpManageServiceImpl.createFacebookLiveVideo]out service.");return result;}