Hướng dẫn này minh hoạ cách tích hợp SDK IMA DAI vào một ứng dụng trình phát video. Nếu bạn muốn xem hoặc làm theo một mẫu tích hợp hoàn chỉnh, hãy tải ví dụ cơ bản xuống từ GitHub.
Tổng quan về IMA DAI
Việc triển khai IMA DAI bao gồm hai thành phần SDK chính như được minh hoạ trong hướng dẫn này:
StreamRequest: Một đối tượng xác định yêu cầu luồng. Yêu cầu về luồng có thể là video theo yêu cầu hoặc sự kiện phát trực tiếp. Yêu cầu phát trực tiếp chỉ định khoá thành phần, trong khi yêu cầu VOD chỉ định mã CMS và mã video. Cả hai loại yêu cầu đều có thể bao gồm khoá API cần thiết để truy cập vào các luồng được chỉ định và mã mạng Google Ad Manager để IMA SDK xử lý giá trị nhận dạng quảng cáo như được chỉ định trong phần cài đặt Google Ad Manager.StreamManager: Một đối tượng xử lý các luồng chèn quảng cáo động và hoạt động tương tác với phần phụ trợ DAI. Trình quản lý luồng cũng xử lý các ping theo dõi và chuyển tiếp các sự kiện quảng cáo và luồng đến nhà xuất bản.
Điều kiện tiên quyết
- Hãy đọc trang về khả năng tương thích của chúng tôi để đảm bảo trường hợp sử dụng mà bạn dự định được hỗ trợ.
- Tải mã trình phát mẫu Roku của chúng tôi xuống
- Triển khai mã trình phát mẫu cho thiết bị Roku để xác minh rằng chế độ thiết lập phát triển của bạn đang hoạt động.
Phát video của bạn
Trình phát video mẫu được cung cấp sẽ phát một video nội dung ngay lập tức. Triển khai trình phát mẫu cho trình phát Roku để đảm bảo môi trường phát triển của bạn được thiết lập đúng cách.
Biến trình phát video của bạn thành trình phát luồng IMA DAI
Hãy làm theo các bước sau để triển khai trình phát trực tuyến.
Tạo Sdk.xml
Thêm một tệp mới vào dự án của bạn cùng với MainScene.xml có tên là Sdk.xml,
rồi thêm mã nguyên mẫu sau:
Sdk.xml
<?xml version = "1.0" encoding = "utf-8" ?>
<component name = "imasdk" extends = "Task">
<interface>
</interface>
<script type = "text/brightscript">
<![CDATA[
' Your code goes here.
]]>
</script>
</component>
Bạn cần chỉnh sửa cả hai tệp này trong suốt hướng dẫn này.
Tải Khung quảng cáo Roku
IMA DAI SDK phụ thuộc vào Roku Advertising Framework. Để tải khung, hãy thêm nội dung sau vào manifest và Sdk.xml:
bs_libs_required=roku_ads_lib,googleima3
Library "Roku_Ads.brs"
Library "IMA3.brs"
Tải IMA DAI SDK
Để tải SDK IMA DAI, hãy làm như sau:
Khởi chạy SDK IMA bằng lệnh gọi
New_IMASDK():sub loadSdk() If m.sdk = invalid m.sdk = New_IMASDK() End If m.top.sdkLoaded = true End SubTheo dõi xem IMA đã tải hay chưa bằng cách tạo một trường boolean
sdkLoaded:<field id="sdkLoaded" type="Boolean" />Gọi chương trình con
loadSdk()từ chương trình conrunThread()chính:if not m.top.sdkLoaded loadSdk() End IfTạo hàm
loadImaSdk()trongMainScene.xmlđể tạo và chạy đối tượngsdkTask:function loadImaSdk() as void m.sdkTask = createObject("roSGNode", "imasdk") m.sdkTask.observeField("sdkLoaded", "onSdkLoaded") m.sdkTask.observeField("errors", "onSdkLoadedError") ' Change to m.testLiveStream to demo live instead of VOD. selectedStream = m.testVodStream m.videoTitle = selectedStream.title m.sdkTask.streamData = selectedStream m.sdkTask.observeField("urlData", "urlLoadRequested") m.sdkTask.video = m.video ' Setting control to run starts the task thread. m.sdkTask.control = "RUN" end functionGọi hàm
loadImaSdk()từ hàminit().Tạo các chương trình con của trình nghe
onSdkLoaded()vàonSdkLoadedError()để phản hồi các sự kiện tải SDK:Sub onSdkLoaded(message as Object) print "----- onSdkLoaded --- control ";message End Sub Sub onSdkLoadedError(message as Object) print "----- errors in the sdk loading process --- ";message End Sub
Tạo trình phát luồng IMA
Để tạo trình phát luồng IMA, hãy làm như sau:
Tạo một chương trình con
setupVideoPlayer()thực hiện những việc sau:Sử dụng phương thức
createPlayer()để tạo trình phát luồng.Yêu cầu trình phát trực tuyến đó triển khai 3 phương thức gọi lại:
loadUrl,adBreakStartedvàadBreakEnded.Tắt chế độ phát nhanh khi luồng được tải để ngăn người dùng bỏ qua quảng cáo trước video ngay khi luồng bắt đầu, trước khi sự kiện bắt đầu điểm chèn quảng cáo được kích hoạt.
sub setupVideoPlayer() sdk = m.sdk m.player = sdk.createPlayer() m.player.top = m.top m.player.loadUrl = Function(urlData) ' This line prevents users from scanning during buffering ' or during the first second of the ad before we have a callback from roku. ' If there are no prerolls disabling trickplay isn't needed. m.top.video.enableTrickPlay = false m.top.urlData = urlData End Function m.player.adBreakStarted = Function(adBreakInfo as Object) print "---- Ad Break Started ---- " m.top.adPlaying = True m.top.video.enableTrickPlay = false End Function m.player.adBreakEnded = Function(adBreakInfo as Object) print "---- Ad Break Ended ---- " m.top.adPlaying = False m.top.video.enableTrickPlay = true End Function m.player.seek = Function(timeSeconds as Double) print "---- SDK requested seek to ----" ; timeSeconds m.top.video.seekMode = "accurate" m.top.video.seek = timeSeconds End Function End SubThêm phương thức gọi lại
seekđể hỗ trợ quảng cáo có thể bỏ qua. Để biết thêm thông tin, hãy xem bài viết Thêm tính năng hỗ trợ quảng cáo có thể bỏ qua.Thêm các trường
urlData,adPlayingvàvideođược dùng trong chương trình consetupVideoPlayer():<field id="urlData" type="assocarray" /> <field id="adPlaying" type="Boolean" /> <field id="video" type="Node" />
Tạo và thực thi yêu cầu luồng
Để yêu cầu luồng DAI, hãy làm như sau:
Tạo một chương trình con
loadStream()để tạo và yêu cầu một luồng. Để hỗ trợ giao diện người dùng quảng cáo, chẳng hạn như biểu tượng Lựa chọn quảng cáo, bạn cũng phải chuyển một tệp đối chiếu đến nút chứa video nội dung của bạn trong yêu cầu:Sub loadStream() sdk = m.sdk sdk.initSdk() setupVideoPlayer() request = {} streamData = m.top.streamData if streamData.type = "live" request = sdk.CreateLiveStreamRequest(streamData.assetKey, streamData.apiKey, streamData.networkCode) else if streamData.type = "vod" request = sdk.CreateVodStreamRequest(streamData.contentSourceId, streamData.videoId, streamData.apiKey, streamData.networkCode) else request = sdk.CreateStreamRequest() end if request.player = m.player request.adUiNode = m.top.video requestResult = sdk.requestStream(request) If requestResult <> Invalid print "Error requesting stream ";requestResult Else m.streamManager = Invalid While m.streamManager = Invalid sleep(50) m.streamManager = sdk.getStreamManager() End While If m.streamManager = Invalid or m.streamManager["type"] <> Invalid or m.streamManager["type"] = "error" errors = CreateObject("roArray", 1, True) print "error ";m.streamManager["info"] errors.push(m.streamManager["info"]) m.top.errors = errors Else m.top.streamManagerReady = True addCallbacks() m.streamManager.start() End If End If End SubThêm các trường
streamDatavàstreamManagerReadyđược dùng trong chương trình conloadStream():<field id="streamManagerReady" type="Boolean" /> <field id="streamData" type="assocarray" />Nếu trình quản lý luồng không hoạt động, hãy gọi chương trình con
loadStream()từ chương trình conrunThread():if not m.top.streamManagerReady loadStream() End IfChọn video theo yêu cầu hoặc sự kiện phát trực tiếp. Ví dụ sau đây có các tham số luồng cho một sự kiện phát trực tiếp và một luồng video theo yêu cầu (VOD):
m.testLiveStream = { title: "Live Stream", assetKey: "c-rArva4ShKVIAkNfy6HUQ", networkCode: "21775744923", apiKey: "", type: "live" } m.testVodStream = { title: "VOD stream" contentSourceId: "2548831", videoId: "tears-of-steel", networkCode: "21775744923", apiKey: "", type: "vod" }Theo mặc định, hướng dẫn này sử dụng luồng VOD. Bạn có thể sử dụng sự kiện phát trực tiếp bằng cách thay đổi biến
selectedStreamtừ đối tượngm.testVodStreamthành đối tượngm.testLiveStream.
Bắt đầu phát trực tiếp
Tạo chương trình con urlLoadRequested() để theo dõi dữ liệu luồng và gọi chương trình con playStream():
Sub urlLoadRequested(message as Object)
print "Url Load Requested ";message
data = message.getData()
playStream(data.manifest, data.format)
End Sub
Tạo playStream() để bắt đầu phát trực tuyến:
Sub playStream(url as String, format as String)
vidContent = createObject("RoSGNode", "ContentNode")
vidContent.url = url
vidContent.title = m.videoTitle
vidContent.streamformat = format
m.video.content = vidContent
m.video.setFocus(true)
m.video.visible = true
m.video.control = "play"
m.video.EnableCookies()
End Sub
Theo dõi siêu dữ liệu của luồng
Tạo chương trình con runLoop() bằng vòng lặp while để chạy trong quá trình phát luồng và gửi siêu dữ liệu luồng đến IMA bằng StreamManager.onMessage():
Sub runLoop()
' Forward all timed metadata events.
m.top.video.timedMetaDataSelectionKeys = ["*"]
' Cycle through all the fields and just listen to them all.
m.port = CreateObject("roMessagePort")
fields = m.top.video.getFields()
for each field in fields
m.top.video.observeField(field, m.port)
end for
while True
msg = wait(1000, m.port)
if m.top.video = invalid
print "exiting"
exit while
end if
m.streamManager.onMessage(msg)
currentTime = m.top.video.position
' Only enable trickplay after a few seconds, in case we start with an ad,
' to prevent users from skipping through that ad.
If currentTime > 3 And not m.top.adPlaying
m.top.video.enableTrickPlay = true
End If
end while
End Sub
Theo dõi các sự kiện quảng cáo
Giờ đây, khi bạn truyền siêu dữ liệu của luồng phát đến IMA, IMA có thể phát ra các sự kiện quảng cáo trong điểm chèn quảng cáo. Tạo trình nghe sự kiện quảng cáo nếu cần để phản hồi các sự kiện quảng cáo:
Function addCallbacks() as Void
m.streamManager.addEventListener(m.sdk.AdEvent.ERROR, errorCallback)
m.streamManager.addEventListener(m.sdk.AdEvent.START, startCallback)
m.streamManager.addEventListener(m.sdk.AdEvent.FIRST_QUARTILE, firstQuartileCallback)
m.streamManager.addEventListener(m.sdk.AdEvent.MIDPOINT, midpointCallback)
m.streamManager.addEventListener(m.sdk.AdEvent.THIRD_QUARTILE, thirdQuartileCallback)
m.streamManager.addEventListener(m.sdk.AdEvent.COMPLETE, completeCallback)
End Function
Function startCallback(ad as Object) as Void
print "Callback from SDK -- Start called - "
End Function
Function firstQuartileCallback(ad as Object) as Void
print "Callback from SDK -- First quartile called - "
End Function
Function midpointCallback(ad as Object) as Void
print "Callback from SDK -- Midpoint called - "
End Function
Function thirdQuartileCallback(ad as Object) as Void
print "Callback from SDK -- Third quartile called - "
End Function
Function completeCallback(ad as Object) as Void
print "Callback from SDK -- Complete called - "
End Function
Function errorCallback(error as Object) as Void
print "Callback from SDK -- Error called - "; error
' errors are critical and should terminate the stream.
m.errorState = True
End Function
Thêm tính năng hỗ trợ quảng cáo có thể bỏ qua (không bắt buộc)
Để hỗ trợ quảng cáo có thể bỏ qua, bạn cần thêm phương thức seek vào đối tượng player của IMA DAI SDK. Phương thức này sẽ tìm video theo lập trình đến vị trí đã chỉ định, tính bằng giây dấu phẩy động.
Để hỗ trợ quảng cáo có thể bỏ qua, bạn cũng phải đảm bảo đặt adUiNode trong yêu cầu của mình.
m.player.seek = Function(timeSeconds as Double)
print "---- SDK requested seek to ----" ; timeSeconds
m.top.video.seekMode = "accurate"
m.top.video.seek = timeSeconds
End Function