230603 TMDB 영화 관련 영상 유튜브 iframe 모달 만들기
TMDB에서 영화 정보와 해당 영화의 관련 영상을 가져오고, iframe으로 모달을 띄우기
- TMDB에서 해당 영화의 비디오 목록 가져오기
- 유튜브에서 비디오 정보 가져오기
- 동영상 정보에서 썸네일 정보 찾기
- IFrame Player API로 유튜브 플레이어 띄우기
1. 영화 상세 페이지의 url에서 query string으로 영화 id값 가져오기
function searchParam(key) {
return new URLSearchParams(location.search).get(key);
}
searchParam('id')
2. TMDB에서 해당 영화의 비디오 목록 가져오기
- TMDB에서 Id값으로 해당 영화의 관련 비디오 목록 가져오기
https://developer.themoviedb.org/reference/movie-videos
Videos
Use the world's best entertainment API to get information about what movies and TV shows are streaming where, as well as all the metadata you need to build an amazing experience yourself.
developer.themoviedb.org
async function fetchMovieVideos(id) {
const res = await fetch(
`https://api.themoviedb.org/3/movie/${id}/videos?language=ko-KR`,
options
);
const { results } = await res.json();
return results;
}
3. 받아온 비디오 목록의 각각 id값으로 유튜브 동영상 썸네일 가져오기
https://developers.google.com/youtube/v3/docs/videos/list?hl=ko
Videos: list | YouTube Data API | Google for Developers
Videos: list 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. API 요청 매개변수와 일치하는 동영상의 목록을 반환합니다. 지금 사용해 보거나 예를 참조하세요.
developers.google.com
async function fetchYoutubeVideos(id) {
const res = await fetch(
`https://content-youtube.googleapis.com/youtube/v3/videos?id=${id}&part=id,snippet&key=${YOUTUBE_APIKEY}`
);
const { items } = await res.json();
if (!items[0]) return undefined;
return {
id: items[0].id,
title: items[0].snippet.title,
url: items[0].snippet.thumbnails.standard.url,
};
}
4. 동영상 플레이어 모달 창 켜고, 끄기
//iframe api 모듈 가져오기
let tag = document.createElement("script");
tag.src = "https://www.youtube.com/iframe_api";
let firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
let player;
function startPlayer(id) {
if (player) {
player.destroy();
player = null;
}
player = new YT.Player("youtube_player", {
height: "360",
width: "640",
videoId: id,
events: {
onReady: onPlayerReady,
},
});
$youtube_player_container.classList.remove("hide");
}
function closePlayer() {
$youtube_player_container.classList.add("hide");
if (player) {
player.destroy();
player = null;
}
}
'내일배움캠프' 카테고리의 다른 글
230605 타입스크립트 클래스 (0) | 2023.06.05 |
---|---|
230604 내일배움캠프 3주차 WIL (0) | 2023.06.04 |
230602 타입스크립트 사용해보기 (0) | 2023.06.02 |
230601 자바스크립트 <script>와 <script type='module'>의 차이 (0) | 2023.06.01 |
230531 자바스크립트 알고리즘 문제 해결을 위한 방법 (0) | 2023.05.31 |