-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
90 lines (78 loc) · 2.54 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const currentContent = document.querySelector("#content");
const currentContentId = currentContent.getAttribute("src");
const currentContentType = currentContent.getAttribute("type");
var muted = currentContent.muted;
const listenLocalPlayerPlayerEvent = (remotePlayer, remotePlayerController) => {
currentContent.addEventListener("play", () => {
remotePlayerController.playOrPause();
});
currentContent.addEventListener("pause", () => {
remotePlayerController.playOrPause();
});
currentContent.addEventListener("seeked", () => {
remotePlayer.currentTime = currentContent.currentTime;
remotePlayerController.seek();
});
currentContent.addEventListener("volumechange", () => {
if ((currentContent.muted && !muted) || (!currentContent.muted && muted)) {
muted = !muted;
remotePlayerController.muteOrUnmute();
} else {
remotePlayer.volumeLevel = currentContent.volume;
remotePlayerController.setVolumeLevel();
}
});
};
const initializeCastSession = (
context,
remotePlayer,
remotePlayerController
) => {
console.log("CastContext: CastSession connected");
const localIsPLaying =
currentContent.currentTime > 0 &&
!currentContent.paused &&
!currentContent.ended;
var mediaInfo = new chrome.cast.media.MediaInfo(
currentContentId,
currentContentType
);
var request = new chrome.cast.media.LoadRequest(mediaInfo);
var castSession = context.getCurrentSession();
request.currentTime = currentContent.currentTime;
if (!localIsPLaying) {
request.autoplay = false;
}
castSession.loadMedia(request).then(
function () {
console.log("Load succeed");
listenLocalPlayerPlayerEvent(remotePlayer, remotePlayerController);
},
function (errorCode) {
console.log("Error code: " + errorCode);
}
);
};
const initializeCastApi = () => {
const context = cast.framework.CastContext.getInstance();
const remotePlayer = new cast.framework.RemotePlayer();
const remotePlayerController = new cast.framework.RemotePlayerController(
remotePlayer
);
context.setOptions({
receiverApplicationId: chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,
});
context.addEventListener(
cast.framework.CastContextEventType.SESSION_STATE_CHANGED,
(event) => {
if (event.sessionState === cast.framework.SessionState.SESSION_STARTED) {
initializeCastSession(context, remotePlayer, remotePlayerController);
}
}
);
};
window["__onGCastApiAvailable"] = function (isAvailable) {
if (isAvailable) {
initializeCastApi();
}
};