OpenTok服务器端SDK
项目描述
OpenTok Python SDK 允许您为会话和令牌生成OpenTok应用程序,并存档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() 方法时传递 ArchiveModes.always 作为 archive_mode 参数来创建自动存档的会话(见上面的“创建会话”)。
对于组合存档,您可以使用 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/获取所有支持选项。
发现错误?在问题页面上提交。提示:测试用例非常有帮助!