ID412 Web

W3

Week 3. Integrating System (API, Sound, Mobile, Unreal)

1. API: Introduction

  • What is ?
    • An application programming interface is a connection between computers or between computer programs. It is a type of software interface, offering a service to other pieces of software. - Wikipedia
  • Various types of APIs
    • Weather, news, maps, public data
    • OpenAI API, Anthropic API (Claude)
    • Replicate API
    • Microsoft Azure/AWS/Google Cloud
  • Integration with Next.js
    • App Router: LINK
      • What is a Route Handler: Create Server-side logic directly in your Next.js without having to create a separate Backend Server
      • app/api/<name>/route.ts → fetch("/api/<name>") from your page
      • Runs on the server. Your API key never reaches the browser
      • Route Handlers DO deploy to Vercel (unlike the socket relay)

2. Using an API

Free APIs

APIDataKey
Open-MeteoWeather, air qualityNo key
USGS EarthquakesEarthquakes of the last hour / day / weekNo key
New York TimesNews: top stories, article searchFree key
NASASpace images and dataFree key
공공데이터포털Korean public dataFree key

Without a key: call it from the page with fetch

const response = await fetch(
  "https://api.open-meteo.com/v1/forecast?latitude=36.37&longitude=127.36&current=temperature_2m,wind_speed_10m",
);
const data = await response.json();
console.log(data.current.temperature_2m, data.current.wind_speed_10m);

With a key: call it from a Route Handler

  • Step 1. Register and create an API Key
  • Step 2. Store your API Key in : NYT_API_KEY=...
    • What is .env.local? Environment variables, read only on the server
    • Do NOT prefix it with NEXT_PUBLIC_. Anything with that prefix is shipped to the browser, i.e. public
  • Step 3. Check : .env* is already there. Your key must never be committed
  • Step 4. Write the API code in a Route Handler: app/api/<name>/route.ts. Read the key with process.env.NYT_API_KEY
  • Step 5. On the frontend, call this Route Handler via fetch

API examples (/experiments/w3)

  1. Weather → wind field (no key): api/weather
  2. NYT headlines (key, Route Handler): api/nyt-headlines → app/api/nyt-headlines/route.ts

LLM API

3. Sound: Tone.js

  • : the browser's audio engine. Oscillators, samples, effects, analysis (volume, FFT)
  • : Javascript library on top of Web Audio, musician-friendly (Synths, Transport, Effects) LINK
  • Already installed in the template: tone
  • Rules
    • Audio starts only after a user gesture (tap/click): await Tone.start() inside an event handler
    • Microphone input requires HTTPS (see W2 A2)
import * as Tone from "tone";

async function play() {
  await Tone.start();
  const synth = new Tone.Synth().toDestination();
  synth.triggerAttackRelease("C4", "8n");
}

Ways to make sound

  1. Synthesis: Tone.Synth, Tone.FatOscillator, Tone.NoiseSynth. Parameters → frequency, volume
  2. Samples: recorded files in public/, played with Tone.Player / Tone.Sampler
  3. Sequencing: Tone.Transport, Tone.Loop. Tempo as a parameter
  4. Effects: Tone.Filter, Tone.Reverb, Tone.Distortion, Tone.FeedbackDelay between the source and the speakers
  5. Microphone as input: Tone.UserMedia + Tone.Meter / Tone.FFT
  6. Speech: the browser's speechSynthesis, or a TTS API through a Route Handler

Sound examples

  1. Tone Pad: pointer → pitch, filter: sound/tone-pad
  2. Data → sound (drone, wind, heartbeat, impacts): w1/snp → sound.ts
  3. Microphone → parameter: w1/video

4.

  • A mobile can control Unreal Engine too, not only a web page. The path is the same as in W2: mobile → relay → output. Here the output is Unreal instead of a browser
  • Example repo: https://github.com/jeanyoon-choi/mobile-to-unreal-realtime-backbone
  • What it does: drag a finger on the mobile, and a sphere in Unreal follows it
    1. The mobile opens a web page with an XY pad
    2. While the finger drags, the page sends its position (x, y) and pressure to the relay over WebSocket, 25 times a second
    3. The relay (Node.js) keeps only the newest position and passes it on to Unreal, 30 times a second
    4. In Unreal, one C++ actor receives it and moves the sphere
  • What is different from our relay: a browser can receive Socket.io messages, Unreal cannot. So the relay sends the last step over UDP, a simpler way of sending data over a network, which Unreal can receive
  • To run it you need Node.js 20 or newer, pnpm 11 and Unreal Engine 5.8
    1. pnpm install, then pnpm dev. This starts the mobile page (port 3000) and the relay (port 4000)
    2. On the mobile, on the same Wi-Fi, open http://<YOUR_IP>:3000
    3. Open unreal/MobileToUnrealBackbone/MobileToUnrealBackbone.uproject in Unreal Engine
    4. Drag on the mobile. The sphere in Unreal moves
  • Folders: apps/mobile/ (the mobile page), relay/ (the relay), unreal/ (the Unreal project), docs/ (how it works, in detail)

5. System & Interaction

Examples (/experiments/w3)

  1. Fish Food (mobile · screen)
    • Mobile: tap or slide on the map to drop food or something bitter into the water
    • System: thousands of goldfish, each following the same few rules: stay with the school, go to food, flee from bitter water. Fright passes from fish to fish
    • Screen: the schools gather around the food and scatter from the bitter cloud
  2. Cloud Field (mobile · screen)
    • Mobile: drag on a map to choose a place in the sky, and set two sliders: pressure and heat
    • System: each mobile is a centre of pressure. Low pressure gathers cloud, high pressure clears it. All mobiles are added up at every pixel
    • Screen: one slow sky of clouds, with sound. Each mobile is one voice
  3. City Walk (mobile · screen)
    • Mobile: drag to walk and turn through Shibuya crossing, seen in first person
    • System: every device builds the same city from the same map data. Each mobile sends where it is, 15 times a second
    • Screen: the whole city from above, with a beam of light on every walker

Appendix. Projection Mapping

  • The 1st-floor gallery (Black Room) has two projectors, one for each wall
  • The picture a projector throws is larger than the wall. Only a part of it lands on the wall
    • Left wall: 1920 × 602 of the picture. Right wall: 1675 × 602
1st-floor gallery: left wall 1920 × 602, right wall 1675 × 602
  • So a page that fills the whole screen does not fit the wall: part of it falls outside. Projection mapping is placing your content exactly on the wall
  • How, in the browser
    1. Make the whole page black. Black means the projector sends no light there, so it cannot be seen
    2. Put one box on the page, and put all of your content inside the box
    3. In the room, move and resize the box until its four edges meet the edges of the wall
  • Example: projection-mapping (left · right) → app/experiments/w3/projection-mapping/
    • One laptop per projector. Open ?side=left on one and ?side=right on the other
    • Four sliders move the box: top, left, width, height. When it fits, write the four numbers into FRAMES at the top of MappingFrame.tsx, then press hide
    • Content.tsx is your content. Give it the size of the box (100%), not of the whole window (100vw / 100vh)
  • Reference: https://github.com/jeanyoon-choi/xdlab-mapping

W3

3주차. 시스템 통합 (API, 사운드, 모바일, Unreal)

1. API 소개

  • 란?
    • 컴퓨터와 컴퓨터, 또는 프로그램과 프로그램 사이를 이어 주는 연결이다. 소프트웨어 인터페이스의 한 종류로, 다른 소프트웨어에 서비스를 제공한다. - Wikipedia
  • API의 종류
    • 날씨, 뉴스, 지도, 공공데이터
    • OpenAI API, Anthropic API (Claude)
    • Replicate API
    • Microsoft Azure/AWS/Google Cloud
  • Next.js와 연동하기
    • App Router: LINK
      • Route Handler를 쓰면 백엔드 서버를 따로 만들지 않고 Next.js 안에 서버 쪽 로직을 바로 작성할 수 있다
      • app/api/<name>/route.ts에 작성 → 페이지에서 fetch("/api/<name>")로 호출
      • 서버에서 실행된다. API key는 브라우저로 절대 넘어가지 않는다
      • Route Handler는 Vercel에 함께 배포된다 (socket relay는 배포되지 않는다)

2. API 사용하기

무료 API

API데이터API key
Open-Meteo날씨, 대기질필요 없음
USGS Earthquakes최근 1시간 / 하루 / 일주일 동안 발생한 지진필요 없음
New York Times뉴스 (주요 기사, 기사 검색)무료 key
NASA우주 이미지와 데이터무료 key
공공데이터포털한국 공공데이터무료 key

API key가 필요 없는 경우: 페이지에서 fetch로 호출한다

const response = await fetch(
  "https://api.open-meteo.com/v1/forecast?latitude=36.37&longitude=127.36&current=temperature_2m,wind_speed_10m",
);
const data = await response.json();
console.log(data.current.temperature_2m, data.current.wind_speed_10m);

API key가 필요한 경우: Route Handler에서 호출한다

  • 1단계. 가입한 뒤 API key를 발급받는다
  • 2단계. API key를 에 저장한다: NYT_API_KEY=...
    • .env.local이란? 환경 변수를 담는 파일. 서버에서만 읽는다
    • 이름 앞에 NEXT_PUBLIC_을 붙이면 안 된다. 이 접두사가 붙은 변수는 모두 브라우저까지 전달된다. 곧 외부에 공개된다는 뜻이다
  • 3단계. 를 확인한다. .env*는 이미 들어 있다. API key는 절대 커밋하면 안 된다
  • 4단계. API를 호출하는 코드를 Route Handler에 작성한다: app/api/<name>/route.ts. API key는 process.env.NYT_API_KEY로 읽어 온다
  • 5단계. 프론트엔드에서는 이 Route Handler를 fetch로 호출한다

API 예제 (/experiments/w3)

  1. 날씨 → 바람의 흐름 (API key 필요 없음): api/weather
  2. NYT 헤드라인 (API key 필요, Route Handler 사용): api/nyt-headlines → app/api/nyt-headlines/route.ts

LLM API

  • LLM API(OpenAI, Anthropic)도 사용법은 같다. API key는 .env.local에 두고, Route Handler에서 호출한다
  • SoTA (2024): AI 아바타 도슨트의 대사를 GPT-4o가 쓴다. 관객이 자리를 떠나면 GPT-4o API → Embeddings API → 토큰 임베딩 간 교차 유사도 행렬 → 선

3. 사운드: Tone.js

  • : 브라우저의 오디오 엔진. oscillator, 샘플, 이펙트, 분석(볼륨, FFT) 기능을 제공한다
  • : Web Audio를 기반으로 만든 Javascript 라이브러리. 음악가에게 친숙한 개념(Synth, Transport, Effect)으로 쓸 수 있다 LINK
  • 템플릿에 이미 설치되어 있다: tone
  • 규칙
    • 사용자가 탭하거나 클릭한 뒤에만 오디오를 시작할 수 있다. 이벤트 핸들러 안에서 await Tone.start()를 호출한다
    • 마이크 입력을 받으려면 HTTPS가 필요하다 (W2 A2 참고)
import * as Tone from "tone";

async function play() {
  await Tone.start();
  const synth = new Tone.Synth().toDestination();
  synth.triggerAttackRelease("C4", "8n");
}

사운드를 만드는 방법

  1. 합성: Tone.Synth, Tone.FatOscillator, Tone.NoiseSynth. 파라미터 → 주파수, 볼륨
  2. 샘플: public/에 넣어 둔 녹음 파일을 Tone.Player / Tone.Sampler로 재생한다
  3. 시퀀싱: Tone.Transport, Tone.Loop. 템포를 파라미터로 쓴다
  4. 이펙트: 소스와 스피커 사이에 Tone.Filter, Tone.Reverb, Tone.Distortion, Tone.FeedbackDelay를 연결한다
  5. 마이크를 입력으로 쓰기: Tone.UserMedia + Tone.Meter / Tone.FFT
  6. 음성: 브라우저의 speechSynthesis를 쓰거나, Route Handler를 거쳐 TTS API를 호출한다

사운드 예제

  1. Tone Pad: 포인터 → 음높이, filter: sound/tone-pad
  2. 데이터 → 사운드 (드론, 바람, 심장 박동, 충격음): w1/snp → sound.ts
  3. 마이크 → 파라미터: w1/video

4.

  • 모바일로 웹 페이지뿐 아니라 Unreal Engine도 조작할 수 있다. 거치는 길은 W2와 같다. 모바일 → relay → 출력. 출력이 브라우저에서 Unreal로 바뀔 뿐이다
  • 예제 레포: https://github.com/jeanyoon-choi/mobile-to-unreal-realtime-backbone
  • 이 예제가 하는 일: 모바일에서 손가락을 드래그하면 Unreal 안의 구(sphere)가 따라 움직인다
    1. 모바일에서 XY 패드가 있는 웹 페이지를 연다
    2. 손가락을 드래그하는 동안 페이지가 손가락 위치(x, y)와 누르는 세기(pressure)를 WebSocket으로 relay에 보낸다. 1초에 25번 보낸다
    3. relay(Node.js)는 가장 최근 위치만 남겨서 Unreal로 넘긴다. 1초에 30번 넘긴다
    4. Unreal에서는 C++ 액터 하나가 이 값을 받아서 구를 움직인다
  • 수업에서 쓰는 relay와 다른 점: 브라우저는 Socket.io 메시지를 받을 수 있지만 Unreal은 받지 못한다. 그래서 relay가 마지막 구간을 UDP로 보낸다. UDP는 네트워크로 데이터를 보내는 더 단순한 방식이고, Unreal이 받을 수 있다
  • 실행하려면 Node.js 20 이상, pnpm 11, Unreal Engine 5.8이 필요하다
    1. pnpm install을 한 뒤 pnpm dev를 실행한다. 모바일용 페이지(3000 포트)와 relay(4000 포트)가 켜진다
    2. 같은 Wi-Fi에 연결한 모바일에서 http://<YOUR_IP>:3000을 연다
    3. Unreal Engine에서 unreal/MobileToUnrealBackbone/MobileToUnrealBackbone.uproject를 연다
    4. 모바일에서 드래그하면 Unreal의 구가 움직인다
  • 폴더 구성: apps/mobile/ (모바일 페이지), relay/ (relay), unreal/ (Unreal 프로젝트), docs/ (동작 방식에 대한 자세한 설명)

5. 시스템 & 인터랙션

예제 (/experiments/w3)

  1. Fish Food (mobile · screen)
    • 모바일: 지도를 탭하거나 문질러서 물에 먹이나 쓴 것을 떨어뜨린다
    • 시스템: 금붕어 수천 마리가 모두 같은 규칙 몇 개를 따른다. 무리와 함께 다니고, 먹이로 모이고, 쓴 물에서는 도망친다. 놀란 상태는 옆 물고기에게 옮겨 간다
    • 스크린: 무리가 먹이 주위로 모여들고, 쓴 물이 퍼지면 흩어진다
  2. Cloud Field (mobile · screen)
    • 모바일: 지도를 드래그해서 하늘에서의 위치를 정하고, 슬라이더 두 개로 기압과 열을 조절한다
    • 시스템: 모바일 한 대가 기압의 중심 하나가 된다. 저기압은 구름을 모으고 고기압은 구름을 걷어 낸다. 픽셀마다 모든 모바일의 영향을 더한다
    • 스크린: 천천히 움직이는 구름 낀 하늘이 소리와 함께 나온다. 모바일 한 대가 소리 하나를 맡는다
  3. City Walk (mobile · screen)
    • 모바일: 드래그해서 시부야 교차로를 1인칭 시점으로 걷고 방향을 바꾼다
    • 시스템: 모든 기기가 같은 지도 데이터로 같은 도시를 만든다. 모바일은 자기 위치를 1초에 15번 보낸다
    • 스크린: 도시 전체를 위에서 내려다본다. 걷는 사람마다 빛기둥이 서 있다

부록. 프로젝션 매핑

  • 1층 갤러리(Black Room)에는 프로젝터가 두 대 있고, 벽 하나에 한 대씩 쏜다
  • 프로젝터가 쏘는 화면은 벽보다 크다. 그래서 화면의 일부만 벽에 맺힌다
    • 왼쪽 벽에는 화면 중 1920 × 602만큼, 오른쪽 벽에는 1675 × 602만큼 맺힌다
1층 갤러리: 왼쪽 벽 1920 × 602, 오른쪽 벽 1675 × 602
  • 따라서 화면 전체를 채우도록 만든 페이지는 벽에 맞지 않고, 일부가 벽 밖으로 나간다. 콘텐츠가 벽에 딱 맞게 놓이도록 조정하는 일이 프로젝션 매핑이다
  • 브라우저에서 하는 방법
    1. 페이지 전체를 검은색으로 만든다. 검은색 부분은 프로젝터가 빛을 쏘지 않아서 보이지 않는다
    2. 페이지 위에 상자를 하나 두고, 콘텐츠를 전부 그 상자 안에 넣는다
    3. 전시장에서 상자의 네 변이 벽의 가장자리와 만날 때까지 상자의 위치와 크기를 조절한다
  • 예제: projection-mapping (left · right) → app/experiments/w3/projection-mapping/
    • 프로젝터 한 대에 노트북 한 대를 연결한다. 한쪽에서는 ?side=left를, 다른 쪽에서는 ?side=right를 연다
    • 슬라이더 네 개(top, left, width, height)로 상자를 움직인다. 벽에 맞으면 그 숫자 네 개를 MappingFrame.tsx 맨 위의 FRAMES에 적어 넣고 hide를 누른다
    • Content.tsx가 내 콘텐츠다. 크기는 창 전체(100vw / 100vh)가 아니라 상자(100%)를 기준으로 잡는다
  • 참고: https://github.com/jeanyoon-choi/xdlab-mapping