OpenTok服务器端SDK
项目描述
OpenTok Python SDK允许您为应用程序生成令牌并存档 OpenTok会话。
使用Pip安装(推荐)
Pip使用PyPI索引帮助管理Python项目的依赖关系。更多信息请访问: http://www.pip-installer.org/en/latest/
将opentok软件包作为项目依赖项添加。最常见的方法是将它添加到您的requirements.txt文件中
opentok>=2.10.0
接下来,安装依赖项
$ pip install -r requirements.txt
使用
初始化
在任何你需要使用该包的文件顶部导入该包。至少你将需要 OpenTok 类。然后使用你自己的 API 密钥和 API 密钥初始化一个 OpenTok 实例。
from opentok import OpenTok
opentok = OpenTok(api_key, api_secret)
创建会话
要创建 OpenTok 会话,请使用 opentok.create_session() 方法。此方法有三个可选的关键字参数:
location 可以设置为包含 IP 地址的字符串。
media_mode 是一个字符串(由 MediaModes 类定义)。这决定了会话是否将使用 OpenTok 媒体路由器 或尝试在客户端之间直接发送流。某些 OpenTok 功能(如存档)需要路由会话。
archive_mode 指定会话是否将被自动存档(always)或不是(manual)。
此方法返回一个 Session 对象。其 session_id 属性在保存到持久存储(如数据库)时非常有用。
# Create a session that attempts to send streams directly between clients (falling back
# to use the OpenTok TURN server to relay streams if the clients cannot connect):
session = opentok.create_session()
from opentok import MediaModes
# A session that uses the OpenTok Media Router, which is required for archiving:
session = opentok.create_session(media_mode=MediaModes.routed)
# An automatically archived session:
session = opentok.create_session(media_mode=MediaModes.routed, archive_mode=ArchiveModes.always)
# A session with a location hint
session = opentok.create_session(location=u'12.34.56.78')
# Store this session ID in the database
session_id = session.session_id
生成令牌
创建会话后,你可以开始为客户端生成令牌,以便连接到它。你可以通过调用 opentok.generate_token(session_id) 方法或在创建 Session 实例后调用 session.generate_token() 方法来生成令牌。两者都有一些可选的关键字参数: role、expire_time、data 和 initial_layout_class_list。
# Generate a Token from just a session_id (fetched from a database)
token = opentok.generate_token(session_id)
# Generate a Token by calling the method on the Session (returned from create_session)
token = session.generate_token()
from opentok import Roles
# Set some options in a token
token = session.generate_token(role=Roles.moderator,
expire_time=int(time.time()) + 10,
data=u'name=Johnny'
initial_layout_class_list=[u'focus'])
处理存档
你只能存档使用 OpenTok 媒体路由器(媒体模式设置为路由)的会话。
你可以使用 opentok.start_archive(session_id) 方法开始录制 OpenTok 会话。此方法接受一个可选的关键字参数 name 以分配存档名称。此方法将返回一个 Archive 实例。请注意,你只能在已连接客户端的会话上开始存档。
archive = opentok.start_archive(session_id, name=u'Important Presentation')
# Store this archive_id in the database
archive_id = archive.id
你也可以通过将 options 参数的 has_audio 或 has_video 属性设置为 false 来禁用音频或视频录制。
archive = opentok.start_archive(session_id, name=u'Important Presentation', has_video=False)
# Store this archive_id in the database
archive_id = archive.id
默认情况下,所有流都记录到单个(组合)文件中。你可以将会话中的不同流记录到单个文件中(而不是单个组合文件),方法是设置 opentok.start_archive() 方法的 output_mode 参数为 OutputModes.individual。
archive = opentok.start_archive(session_id, name=u'Important Presentation', output_mode=OutputModes.individual)
# Store this archive_id in the database
archive_id = archive.id
组合存档(输出模式为 OutputModes.composed)有一个可选的 resolution 参数。如果没有提供值,opentok 平台将使用默认分辨率“640x480”。你可以通过设置 opentok.start_archive() 方法的 resolution 参数将其设置为“1280x720”。
警告:此值不能设置为单个输出模式,将会抛出错误。
archive = opentok.start_archive(session_id, name=u'Important Presentation', resolution="1280x720")
# Store this archive_id in the database
archive_id = archive.id
你可以使用 opentok.stop_archive(archive_id) 方法停止已启动的存档录制。你也可以使用 Archive 实例的 archive.stop() 方法来做这件事。
# Stop an Archive from an archive_id (fetched from database)
opentok.stop_archive(archive_id)
# Stop an Archive from an instance (returned from opentok.start_archive)
archive.stop()
要从存档 ID 获取 Archive 实例(及其所有信息),请使用 opentok.get_archive(archive_id) 方法。
archive = opentok.get_archive(archive_id)
要删除存档,你可以调用 opentok.delete_archive(archive_id) 方法或 Archive 实例的 archive.delete() 方法。
# Delete an Archive from an archive ID (fetched from database)
opentok.delete_archive(archive_id)
# Delete an Archive from an Archive instance (returned from opentok.start_archive or
opentok.get_archive)
archive.delete()
您还可以使用API密钥获取您创建的所有存档列表(最多1000个)。这可以通过调用 opentok.list_archives() 方法来完成。有三个可选的关键字参数:count、offset 和 session_id;它们可以帮助您分页查看结果并按会话ID进行筛选。此方法返回 ArchiveList 类的实例。
archive_list = opentok.list_archive()
# Get a specific Archive from the list
archive = archive_list.items[i]
# Iterate over items
for archive in iter(archive_list):
pass
# Get the total number of Archives for this API Key
total = archive_list.total
请注意,您还可以通过在调用 opentok.create_session() 方法时将 archive_mode 参数传递为 ArchiveModes.always 来创建自动存档的会话(请参阅“创建会话”,见上文)。
对于组合存档,您可以使用 opentok.set_archive_layout(archive_id, type, stylesheet) 方法动态更改布局。
opentok.set_archive_layout('ARCHIVEID', 'horizontalPresentation')
设置组合存档的布局是可选的。默认情况下,组合存档使用 best fit 布局。其他有效值包括:custom、horizontalPresentation、pip 和 verticalPresentation。如果您指定了 custom 布局类型,则需要设置样式表参数。
opentok.set_archive_layout(
'ARCHIVEID',
'custom',
'stream.instructor {position: absolute; width: 100%; height:50%;}'
)
对于其他布局类型,请不要设置样式表属性。有关更多信息,请参阅自定义组合存档的视频布局。
有关存档的更多信息,请参阅OpenTok存档编程指南。
发送信号
一旦创建会话,您就可以向会话中的每个人或特定连接发送信号。您可以通过调用 OpenTok 类的 signal(session_id, payload) 方法来发送信号。payload 参数是一个字典,用于设置 type、data 字段。您还可以通过传递参数 connection_id 来调用该方法,向特定连接发送信号 signal(session_id, data, connection_id)。
# payload structure
payload = {
'type': 'type', #optional
'data': 'signal data' #required
}
connection_id = '2a84cd30-3a33-917f-9150-49e454e01572'
# To send a signal to everyone in the session:
opentok.signal(session_id, payload)
# To send a signal to a specific connection in the session:
opentok.signal(session_id, payload, connection_id)
处理流
您可以通过调用 OpenTok 类的 get_stream(session_id, stream_id) 方法来获取有关流的详细信息。
该方法返回一个包含OpenTok流信息的Stream对象。
id:流ID
videoType:"camera" 或 "screen"
name:流名称(如果客户端在发布流时设置了名称)
layoutClassList:它是一个包含流布局类的数组
session_id = 'SESSIONID'
stream_id = '8b732909-0a06-46a2-8ea8-074e64d43422'
# To get stream info:
stream = opentok.get_stream(session_id, stream_id)
# Stream properties:
print stream.id #8b732909-0a06-46a2-8ea8-074e64d43422
print stream.videoType #camera
print stream.name #stream name
print stream.layoutClassList #['full']
此外,您还可以通过调用 OpenTok 类的 list_streams(session_id) 方法来获取会话中所有流的详细信息。
该方法返回一个包含所有流的StreamList对象。
# To get all streams in a session:
stream_list = opentok.list_streams(session_id)
# Getting the first stream of the list
stream = stream_list.items[0]
# Stream properties:
print stream.id #8b732909-0a06-46a2-8ea8-074e64d43422
print stream.videoType #camera
print stream.name #stream name
print stream.layoutClassList #['full']
您可以通过调用 OpenTok 类的 set_stream_class_lists(session_id, stream_list) 方法来更改会话中流的布局类。
布局类定义了流在组合OpenTok存档布局中的显示方式。
# This list contains the information of the streams that will be updated. Each element
# in the list is a dictionary with two properties: 'id' and 'layoutClassList'. The 'id'
# property is the stream ID (a String), and the 'layoutClassList' is an array of class
# names (Strings) to apply to the stream.
payload = [
{'id': '7b09ec3c-26f9-43d7-8197-f608f13d4fb6', 'layoutClassList': ['focus']},
{'id': '567bc941-6ea0-4c69-97fc-70a740b68976', 'layoutClassList': ['top']},
{'id': '307dc941-0450-4c09-975c-705740d08970', 'layoutClassList': ['bottom']}
]
opentok.set_stream_class_lists('SESSIONID', payload)
有关更多信息,请参阅更改组合存档布局类。
强制断开连接
您的应用程序服务器可以通过调用 OpenTok 类的 force_disconnect(session_id, connection_id) 方法或 Session 类的 force_disconnect(connection_id) 方法来断开客户端与OpenTok会话的连接。
session_id = 'SESSIONID'
connection_id = 'CONNECTIONID'
# To send a request to disconnect a client:
opentok.force_disconnect(session_id, connection_id)
处理SIP互联
您可以将您的SIP平台连接到OpenTok会话,来自SIP电话另一端的音频作为纯音频流添加到OpenTok会话中。OpenTok媒体路由器混合会话中其他流的音频,并将混合音频发送到您的SIP端点。
session_id = u('SESSIONID')
token = u('TOKEN')
sip_uri = u('sip:user@sip.partner.com;transport=tls')
# call the method with the required parameters
sip_call = opentok.dial(session_id, token, sip_uri)
# the method also support aditional options to establish the sip call
options = {
'from': 'from@example.com',
'headers': {
'headerKey': 'headerValue'
},
'auth': {
'username': 'username',
'password': 'password'
},
'secure': True
}
# call the method with aditional options
sip_call = opentok.dial(session_id, token, sip_uri, options)
有关技术细节和安全考虑的更多信息,请参阅OpenTok SIP互联开发者指南。
处理广播
OpenTok广播允许您将实时OpenTok会话与众多观众共享。
您可以使用 opentok.start_broadcast() 方法来为 OpenTok 会话启动直播。这会将会话广播到 HLS(HTTP 直播)或 RTMP 流。
要成功启动会话广播,至少必须有一个客户端连接到会话。
直播广播可以针对一个 HLS 终端和会话同时最多五个 RTMP 服务器。您只能为使用 OpenTok 媒体路由器的会话启动直播;您不能使用媒体模式设置为中继的会话进行直播。
session_id = 'SESSIONID'
options = {
'layout': {
'type': 'custom',
'stylesheet': 'the layout stylesheet (only used with type == custom)'
},
'maxDuration': 5400,
'outputs': {
'hls': {},
'rtmp': [{
'id': 'foo',
'serverUrl': 'rtmp://myfooserver/myfooapp',
'streamName': 'myfoostream'
}, {
'id': 'bar',
'serverUrl': 'rtmp://mybarserver/mybarapp',
'streamName': 'mybarstream'
}]
},
'resolution': '640x480'
}
broadcast = opentok.start_broadcast(session_id, options)
您可以使用 opentok.stop_broadcast(broadcast_id) 方法停止已启动的广播。
# getting the ID from a broadcast object
broadcast_id = broadcast.id
# stop a broadcast
broadcast = opentok.stop_broadcast(broadcast_id)
您可以使用 opentok.get_broadcast(broadcast_id) 方法获取正在进行的广播的详细信息。
broadcast_id = '1748b7070a81464c9759c46ad10d3734'
# get broadcast details
broadcast = opentok.get_broadcast(broadcast_id)
print broadcast.json()
# print result
# {
# "createdAt": 1437676551000,
# "id": "1748b707-0a81-464c-9759-c46ad10d3734",
# "projectId": 100,
# "resolution": "640x480",
# "sessionId": "2_MX4xMDBfjE0Mzc2NzY1NDgwMTJ-TjMzfn4",
# "status": "started",
# "updatedAt": 1437676551000,
# "broadcastUrls": {
# "hls": "http://server/fakepath/playlist.m3u8",
# "rtmp": {
# "bar": {
# "serverUrl": "rtmp://mybarserver/mybarapp",
# "status": "live",
# "streamName": "mybarstream"
# },
# "foo": {
# "serverUrl": "rtmp://myfooserver/myfooapp",
# "status": "live",
# "streamName": "myfoostream"
# }
# }
# }
# }
您可以动态更改直播广播的布局类型。
# Valid values to 'layout_type' are: 'custom', 'horizontalPresentation',
# 'pip' and 'verticalPresentation'
opentok.set_broadcast_layout('BROADCASTID', 'horizontalPresentation')
# if you specify a 'custom' layout type, set the stylesheet parameter:
opentok.set_broadcast_layout(
'BROADCASTID',
'custom',
'stream.instructor {position: absolute; width: 100%; height:50%;}'
)
有关 OpenTok 直播广播的更多信息,请参阅 广播开发者指南。
示例
此存储库中包含两个示例应用程序。要尽快开始,请克隆整个存储库并遵循说明。
文档
参考文档可在 <http://www.tokbox.com/opentok/libraries/server/python/reference/index.html> 找到。
要求
您需要一个 OpenTok API 密钥和 API 密钥,您可以在 https://dashboard.tokbox.com/ 获取。
OpenTok Python SDK 需要 Python 2.6、2.7、3.3、3.4、3.5 或 3.6。
发布说明
有关每个版本的详细信息,请参阅 发布页面。
自 v2.2 以来的重要更改
v2.2.1 的更改
create_session() 方法的默认设置是创建一个媒体模式设置为中继的会话。在 SDK 的早期版本中,默认设置是使用 OpenTok 媒体路由器(媒体模式设置为路由)。在中继会话中,客户端将尝试直接在彼此之间发送流(点对点);如果客户端无法连接(由于防火墙限制),则使用 OpenTok TURN 服务器中继音频视频流。
v2.2.0 的更改
此版本的 SDK 包括与 OpenTok 存档一起工作的支持。
OpenTok.create_session() 方法现在包括一个 media_mode 参数,而不是 p2p 参数。
有关详细信息,请参阅 <http://www.tokbox.com/opentok/libraries/server/python/reference/index.html> 的参考文档。
开发和贡献
支持
请参阅 https://support.tokbox.com/ 了解我们所有的支持选项。
发现错误?在 问题页面 上提交。提示:测试用例非常有帮助!