728x90
반응형

mp3 파일들을 연속으로 재생할 수 있는 웹페이지를 만들었다.

 

처음엔 단순하게 audio 태그를 이용하여 재생했다.

 

데스크톱에서 확인했을 때 잘 동작해서 문제가 없다고 생각했다.

 

그런데 모바일에서 확인해보니 처음 재생은 화면이 꺼져도 끝까지 잘 됐지만 다음 파일이 재생되지 않았다.

 

그래서 화면이 꺼지든가 브라우저가 백그라운드로 가도 재생이 되도록 해보려고 방법을 찾아봤다.

 

그러다가 PWA로 하면 원하는 기능이 되지 않을까 해서 찾아봤다.

 

찾아보니 PWA로 만든 음악 플레이어가 있어서 가능성이 보여 예제를 찾아 만들어 보기로 했다.

 

다음은 예제 코드를 참고하여 간단하게 PWA를 만든 코드 일부분이다.

 

manifest.json 파일을 만들어서 추가한다.

 

홈 화면에 추가했을 때 아이콘과 스플래시 화면이 나오도록 설정할 수 있다.

{
  "description": "Play mp3 files.",
  "display": "standalone",
  "icons": [
    {
      "src": "icon/icon-64.png",
      "sizes": "64x64",
      "type": "image/png"
    }
  ],
  "name": "PWA Test",
  "short_name": "PWA Test",
  "start_url": "/index.html",
  "background_color": "#3367D6",
  "theme_color": "#3367D6"
}

그리고 Service Worker를 등록하면 된다.

 

Service Worker는 브라우저가 백그라운드에서 실행하는 스크립트로 웹페이지와는 별개로 작동하며

 

웹페이지 또는 사용자 상호작용이 필요하지 않은 기능을 사용할 수 있게 해준다.

 

index.htmlService Worker를 등록하는 코드를 추가한다.

...
<head>
  <link rel="manifest" href="/manifest.json">
  <link rel="apple-touch-icon" sizes="180x180" href="/icons/icon-64.png">
</head>
<body>
  <script type="text/javascript">
    if('serviceWorker' in navigator) {
      navigator.serviceWorker
               .register('/pwa-examples/a2hs/sw.js')
               .then(function() { console.log('Service Worker Registered'); });
    }
  </script>
</body>
...

sw.js 파일에 다음 코드를 추가한다.

self.addEventListener('install', function(e) {
  e.waitUntil(
    caches.open('cache').then(function(cache) {
      return cache.addAll([
        '/',
        '/index.html',
        '/script.js',
        '/style.css',
        '/icon.png'
      ]);
    });
  );
});

self.addEventListener('fetch', function(e) {
  e.respondWith(
    caches.match(e.request).then(function(response) {
      return response || fetch(e.request);
    });
  );
});

iOS에서 사파리로 접속한 다음 _홈 화면에 추가_를 하면 설정한 아이콘 모양으로 홈 화면에 추가된다.

 

화면이 꺼지거나 앱을 종료해도 재생이 되는지 테스트했지만 재생이 되지 않았다.

 

하지만 안드로이드에서는 화면이 꺼지거나 앱을 꺼도 재생이 잘되는 것을 확인할 수 있었다.

 

참고 문헌

  1. https://github.com/mdn/pwa-examples

  2. https://developers.google.com/web/fundamentals/web-app-manifest

  3. https://developers.google.com/web/fundamentals/primers/service-workers?hl=ko

반응형

+ Recent posts