CINXE.COM
Audio for Web games - Game development | MDN
<!doctype html><html lang="en-US" prefix="og: https://ogp.me/ns#"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><link rel="icon" href="https://developer.mozilla.org/favicon-48x48.bc390275e955dacb2e65.png"/><link rel="apple-touch-icon" href="https://developer.mozilla.org/apple-touch-icon.528534bba673c38049c2.png"/><meta name="theme-color" content="#ffffff"/><link rel="manifest" href="https://developer.mozilla.org/manifest.f42880861b394dd4dc9b.json"/><link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="MDN Web Docs"/><title>Audio for Web games - Game development | MDN</title><link rel="alternate" title="Audio für Webspiele" href="https://developer.mozilla.org/de/docs/Games/Techniques/Audio_for_Web_Games" hrefLang="de"/><link rel="alternate" title="L'audio dans les jeux Web" href="https://developer.mozilla.org/fr/docs/Games/Techniques/Audio_for_Web_Games" hrefLang="fr"/><link rel="alternate" title="ウェブゲーム用の音声" href="https://developer.mozilla.org/ja/docs/Games/Techniques/Audio_for_Web_Games" hrefLang="ja"/><link rel="alternate" title="Audio for Web games" href="https://developer.mozilla.org/en-US/docs/Games/Techniques/Audio_for_Web_Games" hrefLang="en"/><link rel="preload" as="font" type="font/woff2" href="/static/media/Inter.var.c2fe3cb2b7c746f7966a.woff2" crossorigin=""/><link rel="alternate" type="application/rss+xml" title="MDN Blog RSS Feed" href="https://developer.mozilla.org/en-US/blog/rss.xml" hrefLang="en"/><meta name="description" content="Audio is an important part of any game; it adds feedback and atmosphere. Web-based audio is maturing fast, but there are still many browser differences to navigate. We often need to decide which audio parts are essential to our games' experience and which are nice to have but not essential, and devise a strategy accordingly. This article provides a detailed guide to implementing audio for web games, looking at what works currently across as wide a range of platforms as possible."/><meta property="og:url" content="https://developer.mozilla.org/en-US/docs/Games/Techniques/Audio_for_Web_Games"/><meta property="og:title" content="Audio for Web games - Game development | MDN"/><meta property="og:type" content="website"/><meta property="og:locale" content="en_US"/><meta property="og:description" content="Audio is an important part of any game; it adds feedback and atmosphere. Web-based audio is maturing fast, but there are still many browser differences to navigate. We often need to decide which audio parts are essential to our games' experience and which are nice to have but not essential, and devise a strategy accordingly. This article provides a detailed guide to implementing audio for web games, looking at what works currently across as wide a range of platforms as possible."/><meta property="og:image" content="https://developer.mozilla.org/mdn-social-share.d893525a4fb5fb1f67a2.png"/><meta property="og:image:type" content="image/png"/><meta property="og:image:height" content="1080"/><meta property="og:image:width" content="1920"/><meta property="og:image:alt" content="The MDN Web Docs logo, featuring a blue accent color, displayed on a solid black background."/><meta property="og:site_name" content="MDN Web Docs"/><meta name="twitter:card" content="summary_large_image"/><meta name="twitter:creator" content="MozDevNet"/><link rel="canonical" href="https://developer.mozilla.org/en-US/docs/Games/Techniques/Audio_for_Web_Games"/><style media="print">.article-actions-container,.document-toc-container,.language-menu,.main-menu-toggle,.on-github,.page-footer,.place,.sidebar,.top-banner,.top-navigation-main,ul.prev-next{display:none!important}.main-page-content,.main-page-content pre{padding:2px}.main-page-content pre{border-left-width:2px}</style><script src="/static/js/gtag.js" defer=""></script><script defer="" src="/static/js/main.1b60bff1.js"></script><link href="/static/css/main.959b5ea9.css" rel="stylesheet"/></head><body><script>if(document.body.addEventListener("load",(t=>{t.target.classList.contains("interactive")&&t.target.setAttribute("data-readystate","complete")}),{capture:!0}),window&&document.documentElement){const t={light:"#ffffff",dark:"#1b1b1b"};try{const e=window.localStorage.getItem("theme");e&&(document.documentElement.className=e,document.documentElement.style.backgroundColor=t[e]);const o=window.localStorage.getItem("nop");o&&(document.documentElement.dataset.nop=o)}catch(t){console.warn("Unable to read theme from localStorage",t)}}</script><div id="root"><ul id="nav-access" class="a11y-nav"><li><a id="skip-main" href="#content">Skip to main content</a></li><li><a id="skip-search" href="#top-nav-search-input">Skip to search</a></li><li><a id="skip-select-language" href="#languages-switcher-button">Skip to select language</a></li></ul><div class="page-wrapper document-page"><div class="top-banner loading"><section class="place top container"></section></div><div class="sticky-header-container"><header class="top-navigation "><div class="container "><div class="top-navigation-wrap"><a href="/en-US/" class="logo" aria-label="MDN homepage"><svg id="mdn-docs-logo" xmlns="http://www.w3.org/2000/svg" x="0" y="0" viewBox="0 0 694.9 104.4" style="enable-background:new 0 0 694.9 104.4" xml:space="preserve" role="img"><title>MDN Web Docs</title><path d="M40.3 0 11.7 92.1H0L28.5 0h11.8zm10.4 0v92.1H40.3V0h10.4zM91 0 62.5 92.1H50.8L79.3 0H91zm10.4 0v92.1H91V0h10.4z" class="logo-m"></path><path d="M627.9 95.6h67v8.8h-67v-8.8z" class="logo-_"></path><path d="M367 42h-4l-10.7 30.8h-5.5l-10.8-26h-.4l-10.5 26h-5.2L308.7 42h-3.8v-5.6H323V42h-6.5l6.8 20.4h.4l10.3-26h4.7l11.2 26h.5l5.7-20.3h-6.2v-5.6H367V42zm34.9 20c-.4 3.2-2 5.9-4.7 8.2-2.8 2.3-6.5 3.4-11.3 3.4-5.4 0-9.7-1.6-13.1-4.7-3.3-3.2-5-7.7-5-13.7 0-5.7 1.6-10.3 4.7-14s7.4-5.5 12.9-5.5c5.1 0 9.1 1.6 11.9 4.7s4.3 6.9 4.3 11.3c0 1.5-.2 3-.5 4.7h-25.6c.3 7.7 4 11.6 10.9 11.6 2.9 0 5.1-.7 6.5-2 1.5-1.4 2.5-3 3-4.9l6 .9zM394 51.3c.2-2.4-.4-4.7-1.8-6.9s-3.8-3.3-7-3.3c-3.1 0-5.3 1-6.9 3-1.5 2-2.5 4.4-2.8 7.2H394zm51 2.4c0 5-1.3 9.5-4 13.7s-6.9 6.2-12.7 6.2c-6 0-10.3-2.2-12.7-6.7-.1.4-.2 1.4-.4 2.9s-.3 2.5-.4 2.9h-7.3c.3-1.7.6-3.5.8-5.3.3-1.8.4-3.7.4-5.5V22.3h-6v-5.6H416v27c1.1-2.2 2.7-4.1 4.7-5.7 2-1.6 4.8-2.4 8.4-2.4 4.6 0 8.4 1.6 11.4 4.7 3 3.2 4.5 7.6 4.5 13.4zm-7.7.6c0-4.2-1-7.4-3-9.5-2-2.2-4.4-3.3-7.4-3.3-3.4 0-6 1.2-8 3.7-1.9 2.4-2.9 5-3 7.7V57c0 3 1 5.6 3 7.7s4.5 3.1 7.6 3.1c3.6 0 6.3-1.3 8.1-3.9 1.8-2.7 2.7-5.9 2.7-9.6zm69.2 18.5h-13.2v-7.2c-1.2 2.2-2.8 4.1-4.9 5.6-2.1 1.6-4.8 2.4-8.3 2.4-4.8 0-8.7-1.6-11.6-4.9-2.9-3.2-4.3-7.7-4.3-13.3 0-5 1.3-9.6 4-13.7 2.6-4.1 6.9-6.2 12.8-6.2 5.7 0 9.8 2.2 12.3 6.5V22.3h-8.6v-5.6h15.8v50.6h6v5.5zM493.2 56v-4.4c-.1-3-1.2-5.5-3.2-7.3s-4.4-2.8-7.2-2.8c-3.6 0-6.3 1.3-8.2 3.9-1.9 2.6-2.8 5.8-2.8 9.6 0 4.1 1 7.3 3 9.5s4.5 3.3 7.4 3.3c3.2 0 5.8-1.3 7.8-3.8 2.1-2.6 3.1-5.3 3.2-8zm53.1-1.4c0 5.6-1.8 10.2-5.3 13.7s-8.2 5.3-13.9 5.3-10.1-1.7-13.4-5.1c-3.3-3.4-5-7.9-5-13.5 0-5.3 1.6-9.9 4.7-13.7 3.2-3.8 7.9-5.7 14.2-5.7s11 1.9 14.1 5.7c3 3.7 4.6 8.1 4.6 13.3zm-7.7-.2c0-4-1-7.2-3-9.5s-4.8-3.5-8.2-3.5c-3.6 0-6.4 1.2-8.3 3.7s-2.9 5.6-2.9 9.5c0 3.7.9 6.8 2.8 9.4 1.9 2.6 4.6 3.9 8.3 3.9 3.6 0 6.4-1.3 8.4-3.8 1.9-2.6 2.9-5.8 2.9-9.7zm45 5.8c-.4 3.2-1.9 6.3-4.4 9.1-2.5 2.9-6.4 4.3-11.8 4.3-5.2 0-9.4-1.6-12.6-4.8-3.2-3.2-4.8-7.7-4.8-13.7 0-5.5 1.6-10.1 4.7-13.9 3.2-3.8 7.6-5.7 13.2-5.7 2.3 0 4.6.3 6.7.8 2.2.5 4.2 1.5 6.2 2.9l1.5 9.5-5.9.7-1.3-6.1c-2.1-1.2-4.5-1.8-7.2-1.8-3.5 0-6.1 1.2-7.7 3.7-1.7 2.5-2.5 5.7-2.5 9.6 0 4.1.9 7.3 2.7 9.5 1.8 2.3 4.4 3.4 7.8 3.4 5.2 0 8.2-2.9 9.2-8.8l6.2 1.3zm34.7 1.9c0 3.6-1.5 6.5-4.6 8.5s-7 3-11.7 3c-5.7 0-10.6-1.2-14.6-3.6l1.2-8.8 5.7.6-.2 4.7c1.1.5 2.3.9 3.6 1.1s2.6.3 3.9.3c2.4 0 4.5-.4 6.5-1.3 1.9-.9 2.9-2.2 2.9-4.1 0-1.8-.8-3.1-2.3-3.8s-3.5-1.3-5.8-1.7-4.6-.9-6.9-1.4c-2.3-.6-4.2-1.6-5.7-2.9-1.6-1.4-2.3-3.5-2.3-6.3 0-4.1 1.5-6.9 4.6-8.5s6.4-2.4 9.9-2.4c2.6 0 5 .3 7.2.9 2.2.6 4.3 1.4 6.1 2.4l.8 8.8-5.8.7-.8-5.7c-2.3-1-4.7-1.6-7.2-1.6-2.1 0-3.7.4-5.1 1.1-1.3.8-2 2-2 3.8 0 1.7.8 2.9 2.3 3.6 1.5.7 3.4 1.2 5.7 1.6 2.2.4 4.5.8 6.7 1.4 2.2.6 4.1 1.6 5.7 3 1.4 1.6 2.2 3.7 2.2 6.6zM197.6 73.2h-17.1v-5.5h3.8V51.9c0-3.7-.7-6.3-2.1-7.9-1.4-1.6-3.3-2.3-5.7-2.3-3.2 0-5.6 1.1-7.2 3.4s-2.4 4.6-2.5 6.9v15.6h6v5.5h-17.1v-5.5h3.8V51.9c0-3.8-.7-6.4-2.1-7.9-1.4-1.5-3.3-2.3-5.6-2.3-3.2 0-5.5 1.1-7.2 3.3-1.6 2.2-2.4 4.5-2.5 6.9v15.8h6.9v5.5h-20.2v-5.5h6V42.4h-6.1v-5.6h13.4v6.4c1.2-2.1 2.7-3.8 4.7-5.2 2-1.3 4.4-2 7.3-2s5.3.7 7.5 2.1c2.2 1.4 3.7 3.5 4.5 6.4 1.1-2.5 2.7-4.5 4.9-6.1s4.8-2.4 7.9-2.4c3.5 0 6.5 1.1 8.9 3.3s3.7 5.6 3.7 10.2v18.2h6.1v5.5zm42.5 0h-13.2V66c-1.2 2.2-2.8 4.1-4.9 5.6-2.1 1.6-4.8 2.4-8.3 2.4-4.8 0-8.7-1.6-11.6-4.9-2.9-3.2-4.3-7.7-4.3-13.3 0-5 1.3-9.6 4-13.7 2.6-4.1 6.9-6.2 12.8-6.2s9.8 2.2 12.3 6.5V22.7h-8.6v-5.6h15.8v50.6h6v5.5zm-13.3-16.8V52c-.1-3-1.2-5.5-3.2-7.3s-4.4-2.8-7.2-2.8c-3.6 0-6.3 1.3-8.2 3.9-1.9 2.6-2.8 5.8-2.8 9.6 0 4.1 1 7.3 3 9.5s4.5 3.3 7.4 3.3c3.2 0 5.8-1.3 7.8-3.8 2.1-2.6 3.1-5.3 3.2-8zm61.5 16.8H269v-5.5h6V51.9c0-3.7-.7-6.3-2.2-7.9-1.4-1.6-3.4-2.3-5.7-2.3-3.1 0-5.6 1-7.4 3s-2.8 4.4-2.9 7v15.9h6v5.5h-19.3v-5.5h6V42.4h-6.2v-5.6h13.6V43c2.6-4.6 6.8-6.9 12.7-6.9 3.6 0 6.7 1.1 9.2 3.3s3.7 5.6 3.7 10.2v18.2h6v5.4h-.2z" class="logo-text"></path></svg></a><button title="Open main menu" type="button" class="button action has-icon main-menu-toggle" aria-haspopup="menu" aria-label="Open main menu" aria-expanded="false"><span class="button-wrap"><span class="icon icon-menu "></span><span class="visually-hidden">Open main menu</span></span></button></div><div class="top-navigation-main"><nav class="main-nav" aria-label="Main menu"><ul class="main-menu nojs"><li class="top-level-entry-container "><button type="button" id="references-button" class="top-level-entry menu-toggle" aria-controls="references-menu" aria-expanded="false">References</button><a href="/en-US/docs/Web" class="top-level-entry">References</a><ul id="references-menu" class="submenu references hidden inline-submenu-lg" aria-labelledby="references-button"><li class="apis-link-container mobile-only "><a href="/en-US/docs/Web" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">Overview / Web Technology</div><p class="submenu-item-description">Web technology reference for developers</p></div></a></li><li class="html-link-container "><a href="/en-US/docs/Web/HTML" class="submenu-item "><div class="submenu-icon html"></div><div class="submenu-content-container"><div class="submenu-item-heading">HTML</div><p class="submenu-item-description">Structure of content on the web</p></div></a></li><li class="css-link-container "><a href="/en-US/docs/Web/CSS" class="submenu-item "><div class="submenu-icon css"></div><div class="submenu-content-container"><div class="submenu-item-heading">CSS</div><p class="submenu-item-description">Code used to describe document style</p></div></a></li><li class="javascript-link-container "><a href="/en-US/docs/Web/JavaScript" class="submenu-item "><div class="submenu-icon javascript"></div><div class="submenu-content-container"><div class="submenu-item-heading">JavaScript</div><p class="submenu-item-description">General-purpose scripting language</p></div></a></li><li class="http-link-container "><a href="/en-US/docs/Web/HTTP" class="submenu-item "><div class="submenu-icon http"></div><div class="submenu-content-container"><div class="submenu-item-heading">HTTP</div><p class="submenu-item-description">Protocol for transmitting web resources</p></div></a></li><li class="apis-link-container "><a href="/en-US/docs/Web/API" class="submenu-item "><div class="submenu-icon apis"></div><div class="submenu-content-container"><div class="submenu-item-heading">Web APIs</div><p class="submenu-item-description">Interfaces for building web applications</p></div></a></li><li class="apis-link-container "><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">Web Extensions</div><p class="submenu-item-description">Developing extensions for web browsers</p></div></a></li><li class="apis-link-container desktop-only "><a href="/en-US/docs/Web" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">Web Technology</div><p class="submenu-item-description">Web technology reference for developers</p></div></a></li></ul></li><li class="top-level-entry-container "><button type="button" id="guides-button" class="top-level-entry menu-toggle" aria-controls="guides-menu" aria-expanded="false">Guides</button><a href="/en-US/docs/Learn" class="top-level-entry">Guides</a><ul id="guides-menu" class="submenu guides hidden inline-submenu-lg" aria-labelledby="guides-button"><li class="apis-link-container mobile-only "><a href="/en-US/docs/Learn" class="submenu-item "><div class="submenu-icon learn"></div><div class="submenu-content-container"><div class="submenu-item-heading">Overview / MDN Learning Area</div><p class="submenu-item-description">Learn web development</p></div></a></li><li class="apis-link-container desktop-only "><a href="/en-US/docs/Learn" class="submenu-item "><div class="submenu-icon learn"></div><div class="submenu-content-container"><div class="submenu-item-heading">MDN Learning Area</div><p class="submenu-item-description">Learn web development</p></div></a></li><li class="html-link-container "><a href="/en-US/docs/Learn/HTML" class="submenu-item "><div class="submenu-icon html"></div><div class="submenu-content-container"><div class="submenu-item-heading">HTML</div><p class="submenu-item-description">Learn to structure web content with HTML</p></div></a></li><li class="css-link-container "><a href="/en-US/docs/Learn/CSS" class="submenu-item "><div class="submenu-icon css"></div><div class="submenu-content-container"><div class="submenu-item-heading">CSS</div><p class="submenu-item-description">Learn to style content using CSS</p></div></a></li><li class="javascript-link-container "><a href="/en-US/docs/Learn/JavaScript" class="submenu-item "><div class="submenu-icon javascript"></div><div class="submenu-content-container"><div class="submenu-item-heading">JavaScript</div><p class="submenu-item-description">Learn to run scripts in the browser</p></div></a></li><li class=" "><a href="/en-US/docs/Web/Accessibility" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">Accessibility</div><p class="submenu-item-description">Learn to make the web accessible to all</p></div></a></li></ul></li><li class="top-level-entry-container "><button type="button" id="mdn-plus-button" class="top-level-entry menu-toggle" aria-controls="mdn-plus-menu" aria-expanded="false">Plus</button><a href="/en-US/plus" class="top-level-entry">Plus</a><ul id="mdn-plus-menu" class="submenu mdn-plus hidden inline-submenu-lg" aria-labelledby="mdn-plus-button"><li class=" "><a href="/en-US/plus" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">Overview</div><p class="submenu-item-description">A customized MDN experience</p></div></a></li><li class=" "><a href="/en-US/plus/ai-help" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">AI Help</div><p class="submenu-item-description">Get real-time assistance and support</p></div></a></li><li class=" "><a href="/en-US/plus/updates" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">Updates</div><p class="submenu-item-description">All browser compatibility updates at a glance</p></div></a></li><li class=" "><a href="/en-US/plus/docs/features/overview" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">Documentation</div><p class="submenu-item-description">Learn how to use MDN Plus</p></div></a></li><li class=" "><a href="/en-US/plus/docs/faq" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">FAQ</div><p class="submenu-item-description">Frequently asked questions about MDN Plus</p></div></a></li></ul></li><li class="top-level-entry-container "><a class="top-level-entry menu-link" href="/en-US/curriculum/">Curriculum <sup class="new">New</sup></a></li><li class="top-level-entry-container "><a class="top-level-entry menu-link" href="/en-US/blog/">Blog</a></li><li class="top-level-entry-container "><button type="button" id="tools-button" class="top-level-entry menu-toggle" aria-controls="tools-menu" aria-expanded="false">Tools</button><ul id="tools-menu" class="submenu tools hidden inline-submenu-lg" aria-labelledby="tools-button"><li class=" "><a href="/en-US/play" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">Playground</div><p class="submenu-item-description">Write, test and share your code</p></div></a></li><li class=" "><a href="/en-US/observatory" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">HTTP Observatory</div><p class="submenu-item-description">Scan a website for free</p></div></a></li><li class=" "><a href="/en-US/plus/ai-help" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">AI Help</div><p class="submenu-item-description">Get real-time assistance and support</p></div></a></li></ul></li></ul></nav><div class="header-search"><form action="/en-US/search" class="search-form search-widget" id="top-nav-search-form" role="search"><label id="top-nav-search-label" for="top-nav-search-input" class="visually-hidden">Search MDN</label><input aria-activedescendant="" aria-autocomplete="list" aria-controls="top-nav-search-menu" aria-expanded="false" aria-labelledby="top-nav-search-label" autoComplete="off" id="top-nav-search-input" role="combobox" type="search" class="search-input-field" name="q" placeholder=" " required="" value=""/><button type="button" class="button action has-icon clear-search-button"><span class="button-wrap"><span class="icon icon-cancel "></span><span class="visually-hidden">Clear search input</span></span></button><button type="submit" class="button action has-icon search-button"><span class="button-wrap"><span class="icon icon-search "></span><span class="visually-hidden">Search</span></span></button><div id="top-nav-search-menu" role="listbox" aria-labelledby="top-nav-search-label"></div></form></div><div class="theme-switcher-menu"><button type="button" class="button action has-icon theme-switcher-menu small" aria-haspopup="menu"><span class="button-wrap"><span class="icon icon-theme-os-default "></span>Theme</span></button></div><ul class="auth-container"><li><a href="/users/fxa/login/authenticate/?next=%2Fen-US%2Fdocs%2FGames%2FTechniques%2FAudio_for_Web_Games" class="login-link" rel="nofollow">Log in</a></li><li><a href="/users/fxa/login/authenticate/?next=%2Fen-US%2Fdocs%2FGames%2FTechniques%2FAudio_for_Web_Games" target="_self" rel="nofollow" class="button primary mdn-plus-subscribe-link"><span class="button-wrap">Sign up for free</span></a></li></ul></div></div></header><div class="article-actions-container"><div class="container"><button type="button" class="button action has-icon sidebar-button" aria-label="Expand sidebar" aria-expanded="false" aria-controls="sidebar-quicklinks"><span class="button-wrap"><span class="icon icon-sidebar "></span></span></button><nav class="breadcrumbs-container" aria-label="Breadcrumb"><ol typeof="BreadcrumbList" vocab="https://schema.org/" aria-label="breadcrumbs"><li property="itemListElement" typeof="ListItem"><a href="/en-US/docs/Games" class="breadcrumb" property="item" typeof="WebPage"><span property="name">Game development</span></a><meta property="position" content="1"/></li><li property="itemListElement" typeof="ListItem"><a href="/en-US/docs/Games/Techniques" class="breadcrumb" property="item" typeof="WebPage"><span property="name">Techniques for game development</span></a><meta property="position" content="2"/></li><li property="itemListElement" typeof="ListItem"><a href="/en-US/docs/Games/Techniques/Audio_for_Web_Games" class="breadcrumb-current-page" property="item" typeof="WebPage"><span property="name">Audio for Web games</span></a><meta property="position" content="3"/></li></ol></nav><div class="article-actions"><button type="button" class="button action has-icon article-actions-toggle" aria-label="Article actions"><span class="button-wrap"><span class="icon icon-ellipses "></span><span class="article-actions-dialog-heading">Article Actions</span></span></button><ul class="article-actions-entries"><li class="article-actions-entry"><div class="languages-switcher-menu open-on-focus-within"><button id="languages-switcher-button" type="button" class="button action small has-icon languages-switcher-menu" aria-haspopup="menu"><span class="button-wrap"><span class="icon icon-language "></span>English (US)</span></button><div class="hidden"><ul class="submenu language-menu " aria-labelledby="language-menu-button"><li class=" "><form class="submenu-item locale-redirect-setting"><div class="group"><label class="switch"><input type="checkbox" name="locale-redirect"/><span class="slider"></span><span class="label">Remember language</span></label><a href="https://github.com/orgs/mdn/discussions/739" rel="external noopener noreferrer" target="_blank" title="Enable this setting to automatically switch to this language when it's available. (Click to learn more.)"><span class="icon icon-question-mark "></span></a></div></form></li><li class=" "><a data-locale="de" href="/de/docs/Games/Techniques/Audio_for_Web_Games" class="button submenu-item"><span>Deutsch</span><span title="Diese Übersetzung ist Teil eines Experiments."><span class="icon icon-experimental "></span></span></a></li><li class=" "><a data-locale="fr" href="/fr/docs/Games/Techniques/Audio_for_Web_Games" class="button submenu-item"><span>Français</span></a></li><li class=" "><a data-locale="ja" href="/ja/docs/Games/Techniques/Audio_for_Web_Games" class="button submenu-item"><span>日本語</span></a></li></ul></div></div></li></ul></div></div></div></div><div class="main-wrapper"><div class="sidebar-container"><aside id="sidebar-quicklinks" class="sidebar" data-macro="GamesSidebar"><button type="button" class="button action backdrop" aria-label="Collapse sidebar"><span class="button-wrap"></span></button><nav aria-label="Related Topics" class="sidebar-inner"><header class="sidebar-actions"><section class="sidebar-filter-container"><div class="sidebar-filter "><label id="sidebar-filter-label" class="sidebar-filter-label" for="sidebar-filter-input"><span class="icon icon-filter"></span><span class="visually-hidden">Filter sidebar</span></label><input id="sidebar-filter-input" autoComplete="off" class="sidebar-filter-input-field false" type="text" placeholder="Filter" value=""/><button type="button" class="button action has-icon clear-sidebar-filter-button"><span class="button-wrap"><span class="icon icon-cancel "></span><span class="visually-hidden">Clear filter input</span></span></button></div></section></header><div class="sidebar-inner-nav"><div class="in-nav-toc"><div class="document-toc-container"><section class="document-toc"><header><h2 class="document-toc-heading">In this article</h2></header><ul class="document-toc-list"><li class="document-toc-item "><a class="document-toc-link" href="#mobile_audio_caveats">Mobile audio caveats</a></li><li class="document-toc-item "><a class="document-toc-link" href="#mobile_workarounds">Mobile workarounds</a></li><li class="document-toc-item "><a class="document-toc-link" href="#see_also">See also</a></li></ul></section></div></div><div class="sidebar-body"> <ol> <li class="toggle"> <details> <summary>Introduction</summary> <ol> <li><a href="/en-US/docs/Games/Introduction">Introduction</a></li> <li><a href="/en-US/docs/Games/Anatomy">Anatomy</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>APIs for game development</summary> <ol> <li><a href="/en-US/docs/Web/API/Canvas_API">Canvas</a></li> <li><a href="/en-US/docs/Web/CSS">CSS</a></li> <li><a href="/en-US/docs/Web/API/Fullscreen_API">Full screen</a></li> <li><a href="/en-US/docs/Web/API/Gamepad_API">Gamepad</a></li> <li><a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a></li> <li><a href="/en-US/docs/Web/JavaScript">JavaScript</a></li> <li><a href="/en-US/docs/Web/API/Pointer_Lock_API">Pointer Lock</a></li> <li><a href="/en-US/docs/Web/SVG">SVG</a></li> <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray">Typed Arrays</a></li> <li><a href="/en-US/docs/Web/API/Web_Audio_API">Web Audio</a></li> <li><a href="/en-US/docs/Web/API/WebGL_API">WebGL</a></li> <li><a href="/en-US/docs/Web/API/WebRTC_API">WebRTC</a></li> <li><a href="/en-US/docs/Web/API/WebSockets_API">WebSockets</a></li> <li><a href="/en-US/docs/Web/API/WebVR_API">WebVR</a></li> <li><a href="/en-US/docs/Web/API/Web_Workers_API">Web Workers</a></li> <li><a href="/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a></li> </ol> </details> </li> <li class="toggle"> <details open=""> <summary>Techniques</summary> <ol> <li><a href="/en-US/docs/Games/Techniques/Async_scripts">Using async scripts for asm.js</a></li> <li><a href="/en-US/docs/Web/Performance/Optimizing_startup_performance">Optimizing startup performance</a></li> <li><a href="/en-US/docs/Games/Techniques/WebRTC_data_channels">Using WebRTC peer-to-peer data channels</a></li> <li><em><a href="/en-US/docs/Games/Techniques/Audio_for_Web_Games" aria-current="page">Audio for Web Games</a></em></li> <li><a href="/en-US/docs/Games/Techniques/2D_collision_detection">2D collision detection</a></li> <li><a href="/en-US/docs/Games/Techniques/Tilemaps">Tiles and tilemaps overview</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>3D games on the Web</summary> <ol> <li><a href="/en-US/docs/Games/Techniques/3D_on_the_web">3D games on the Web overview</a></li> <li><a href="/en-US/docs/Games/Techniques/3D_on_the_web/Basic_theory">Explaining basic 3D theory</a></li> <li><a href="/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_A-Frame">Building up a basic demo with A-Frame</a></li> <li><a href="/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_Babylon.js">Building up a basic demo with Babylon.js</a></li> <li><a href="/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas">Building up a basic demo with PlayCanvas</a></li> <li><a href="/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_Three.js">Building up a basic demo with Three.js</a></li> <li><a href="/en-US/docs/Games/Techniques/3D_on_the_web/WebXR">WebXR</a></li> <li><a href="/en-US/docs/Games/Techniques/3D_collision_detection">3D collision detection</a></li> <li><a href="/en-US/docs/Games/Techniques/3D_collision_detection/Bounding_volume_collision_detection_with_THREE.js">Bounding volume collision detection with THREE.js</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>Implementing game control mechanisms</summary> <ol> <li><a href="/en-US/docs/Games/Techniques/Control_mechanisms">Control mechanisms</a></li> <li><a href="/en-US/docs/Games/Techniques/Control_mechanisms/Mobile_touch">Mobile touch</a></li> <li><a href="/en-US/docs/Games/Techniques/Control_mechanisms/Desktop_with_mouse_and_keyboard">Desktop with mouse and keyboard</a></li> <li><a href="/en-US/docs/Games/Techniques/Control_mechanisms/Desktop_with_gamepad">Desktop with gamepad</a></li> <li><a href="/en-US/docs/Games/Techniques/Control_mechanisms/Other">Other</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>Tutorials</summary> <ol> <li><a href="/en-US/docs/Games/Tutorials/2D_Breakout_game_pure_JavaScript">2D breakout game using pure JavaScript</a></li> <li><a href="/en-US/docs/Games/Tutorials/2D_breakout_game_Phaser">2D breakout game using Phaser</a></li> <li><a href="/en-US/docs/Games/Tutorials/HTML5_Gamedev_Phaser_Device_Orientation">2D maze_game with device orientation</a></li> <li><a href="https://mozdevs.github.io/html5-games-workshop/en/guides/platformer/start-here/">2D platform game using Phaser</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>Publishing games</summary> <ol> <li><a href="/en-US/docs/Games/Publishing_games">Publishing games overview</a></li> <li><a href="/en-US/docs/Games/Publishing_games/Game_distribution">Game distribution</a></li> <li><a href="/en-US/docs/Games/Publishing_games/Game_promotion">Game promotion</a></li> <li><a href="/en-US/docs/Games/Publishing_games/Game_monetization">Game monetization</a></li> </ol> </details> </li> </ol> </div></div><section class="place side"></section></nav></aside><div class="toc-container"><aside class="toc"><nav><div class="document-toc-container"><section class="document-toc"><header><h2 class="document-toc-heading">In this article</h2></header><ul class="document-toc-list"><li class="document-toc-item "><a class="document-toc-link" href="#mobile_audio_caveats">Mobile audio caveats</a></li><li class="document-toc-item "><a class="document-toc-link" href="#mobile_workarounds">Mobile workarounds</a></li><li class="document-toc-item "><a class="document-toc-link" href="#see_also">See also</a></li></ul></section></div></nav></aside><section class="place side"></section></div></div><main id="content" class="main-content "><article class="main-page-content" lang="en-US"><header><h1>Audio for Web games</h1></header><div class="section-content"><p>Audio is an important part of any game; it adds feedback and atmosphere. Web-based audio is maturing fast, but there are still many browser differences to navigate. We often need to decide which audio parts are essential to our games' experience and which are nice to have but not essential, and devise a strategy accordingly. This article provides a detailed guide to implementing audio for web games, looking at what works currently across as wide a range of platforms as possible.</p></div><section aria-labelledby="mobile_audio_caveats"><h2 id="mobile_audio_caveats"><a href="#mobile_audio_caveats">Mobile audio caveats</a></h2><div class="section-content"><p>By far the most difficult platforms to provide web audio support for are mobile platforms. Unfortunately these are also the platforms that people often use to play games. There are a couple of differences between desktop and mobile browsers that may have caused browser vendors to make choices that can make web audio difficult for game developers to work with. Let's look at these now.</p></div></section><section aria-labelledby="autoplay"><h3 id="autoplay"><a href="#autoplay">Autoplay</a></h3><div class="section-content"><p>Browser autoplay policy now affects desktop <em>and</em> mobile browsers. There is further information about it <a href="https://developer.chrome.com/blog/autoplay/" class="external" target="_blank">here from the Google Developers site</a>.</p> <p>It is worth noting that autoplay with sound is allowed if:</p> <ul> <li>the User has interacted with the domain.</li> <li>on mobile the user has <a href="/en-US/docs/Web/Progressive_web_apps/Guides/Making_PWAs_installable">made the application installable</a>.</li> </ul> <p>Many browsers will ignore any requests made by your game to automatically play audio; instead playback for audio needs to be started by a user-initiated event, such as a click or tap. This means you will have to structure your audio playback to take account of that. This is usually mitigated against by loading the audio in advance and priming it on a user-initiated event.</p> <p>For more passive audio autoplay, for example background music that starts as soon as a game loads, one trick is to detect <em>any</em> user initiated event and start playback then. For other more active sounds that are to be used during the game we could consider priming them as soon as something like a <em>Start</em> button is pressed.</p> <p>To prime audio like this we want to play a part of it; for this reason it is useful to include a moment of silence at the end of your audio sample. Jumping to, playing, and then pausing that silence will mean we can now use JavaScript to play that file at arbitrary points. You can find out more about <a href="/en-US/docs/Web/API/Web_Audio_API/Best_practices#autoplay_policy">best practices with the autoplay policy here</a>.</p> <div class="notecard note"> <p><strong>Note:</strong> Playing part of your file at zero volume could also work if the browser allows you to change volume (see below). Also note that playing and immediately pausing your audio does not guarantee that a small piece of audio won't be played.</p> </div> <div class="notecard note"> <p><strong>Note:</strong> Adding a web app to your mobile's homescreen may change its capabilities. In the case of autoplay on iOS, this appears to be the case currently. If possible, you should try your code on several devices and platforms to see how it works.</p> </div></div></section><section aria-labelledby="volume"><h3 id="volume"><a href="#volume">Volume</a></h3><div class="section-content"><p>Programmatic volume control may be disabled in mobile browsers. The reason often given is that the user should be in control of the volume at the OS level and this shouldn't be overridden.</p></div></section><section aria-labelledby="buffering_and_preloading"><h3 id="buffering_and_preloading"><a href="#buffering_and_preloading">Buffering and preloading</a></h3><div class="section-content"><p>Likely as an attempt to mitigate runaway mobile network data use, we also often find that buffering is disabled before playback has been initiated. Buffering is the process of the browser downloading the media in advance, which we often need to do to ensure smooth playback.</p> <p>The <a href="/en-US/docs/Web/API/HTMLMediaElement"><code>HTMLMediaElement</code></a> interface comes with <a href="/en-US/docs/Web/API/HTMLMediaElement#instance_properties">lots of properties</a> to help determine whether a track is in a state to be playable.</p> <div class="notecard note"> <p><strong>Note:</strong> In many ways the concept of buffering is an outdated one. As long as byte-range requests are accepted (which is the default behavior), we should be able to jump to a specific point in the audio without having to download the preceding content. However, preloading is still useful — without it, there would always need to be some client-server communication required before playing can commence.</p> </div></div></section><section aria-labelledby="concurrent_audio_playback"><h3 id="concurrent_audio_playback"><a href="#concurrent_audio_playback">Concurrent audio playback</a></h3><div class="section-content"><p>A requirement of many games is the need to play more than one piece of audio at the same time; for example, there might be background music playing along with sound effects for various things happening in the game. Although the situation is soon going to get better with the adoption of the <a href="/en-US/docs/Web/API/Web_Audio_API">Web Audio API</a>, the current most widely-supported method — using the vanilla <a href="/en-US/docs/Web/HTML/Element/audio"><code><audio></code></a> element — leads to patchy results on mobile devices.</p></div></section><section aria-labelledby="testing_and_support"><h3 id="testing_and_support"><a href="#testing_and_support">Testing and support</a></h3><div class="section-content"><p>Here's a table that shows what mobile platforms support the features talked about above.</p> <figure class="table-container"><table class="standard-table"> <caption>Mobile support for web audio features</caption> <thead> <tr> <th scope="row">Mobile browser</th> <th scope="col">Version</th> <th scope="col">Concurrent play</th> <th scope="col">Autoplay</th> <th scope="col">Volume adjusting</th> <th scope="col">Preload</th> </tr> </thead> <tbody> <tr> <th scope="row">Chrome (Android)</th> <td>69+</td> <td>Y</td> <td>Y</td> <td>Y</td> <td>Y</td> </tr> <tr> <th scope="row">Firefox (Android)</th> <td>62+</td> <td>Y</td> <td>Y</td> <td>Y</td> <td>Y</td> </tr> <tr> <th scope="row">Edge Mobile</th> <td></td> <td>Y</td> <td>Y</td> <td>Y</td> <td>Y</td> </tr> <tr> <th scope="row">Opera Mobile</th> <td>46+</td> <td>Y</td> <td>Y</td> <td>Y</td> <td>Y</td> </tr> <tr> <th scope="row">Safari (iOS)</th> <td>7+</td> <td>Y/N*</td> <td>N</td> <td>N</td> <td>Y</td> </tr> <tr> <th scope="row">Android Browser</th> <td>67+</td> <td>Y</td> <td>Y</td> <td>Y</td> <td>Y</td> </tr> </tbody> </table></figure> <p>There's a <a href="/en-US/docs/Web/API/HTMLMediaElement#browser_compatibility">full compatibility chart for mobile and desktop HTMLMediaElement support here</a>.</p> <div class="notecard note"> <p><strong>Note:</strong> Concurrent audio playback is tested using our <a href="https://jsfiddle.net/dmkyaq0r/" class="external" target="_blank">concurrent audio test example</a>, where we attempt to play three pieces of audio at the same time using the standard audio API.</p> </div> <div class="notecard note"> <p><strong>Note:</strong> Simple autoplay functionality is tested with our <a href="https://jsfiddle.net/vpdspp2b/" class="external" target="_blank">autoplay test example</a>.</p> </div> <div class="notecard note"> <p><strong>Note:</strong> Volume changeability is tested with our <a href="https://jsfiddle.net/7ta12vw4/" class="external" target="_blank">volume test example</a>.</p> </div></div></section><section aria-labelledby="mobile_workarounds"><h2 id="mobile_workarounds"><a href="#mobile_workarounds">Mobile workarounds</a></h2><div class="section-content"><p>Although mobile browsers can present problems, there are ways to work around the issues detailed above.</p></div></section><section aria-labelledby="audio_sprites"><h3 id="audio_sprites"><a href="#audio_sprites">Audio sprites</a></h3><div class="section-content"><p>Audio sprites borrow their name from <a href="/en-US/docs/Web/CSS/CSS_images/Implementing_image_sprites_in_CSS">CSS sprites</a>, which is a visual technique for using CSS with a single graphic resource to break it into a series of sprites. We can apply the same principle to audio so that rather than having a bunch of small audio files that take time to load and play, we have one larger audio file containing all the smaller audio snippets we need. To play a specific sound from the file, we just use the known start and stop times for each audio sprite.</p> <p>The advantage is that we can prime one piece of audio and have our sprites ready to go. To do this we can just play and instantly pause the larger piece of audio. You'll also reduce the number of server requests and save bandwidth.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>const myAudio = document.createElement("audio"); myAudio.src = "my-sprite.mp3"; myAudio.play(); myAudio.pause(); </code></pre></div> <p>You'll need to sample the current time to know when to stop. If you space your individual sounds by at least 500ms then using the <code>timeUpdate</code> event (which fires every 250ms) should be sufficient. Your files may be slightly longer than they strictly need to be, but silence compresses well.</p> <p>Here's an example of an audio sprite player — first let's set up the user interface in HTML:</p> <div class="code-example"><div class="example-header"><span class="language-name">html</span></div><pre class="brush: html notranslate"><code><audio id="myAudio" src="http://jPlayer.org/tmp/countdown.mp3"></audio> <button data-start="18" data-stop="19">0</button> <button data-start="16" data-stop="17">1</button> <button data-start="14" data-stop="15">2</button> <button data-start="12" data-stop="13">3</button> <button data-start="10" data-stop="11">4</button> <button data-start="8" data-stop="9">5</button> <button data-start="6" data-stop="7">6</button> <button data-start="4" data-stop="5">7</button> <button data-start="2" data-stop="3">8</button> <button data-start="0" data-stop="1">9</button> </code></pre></div> <p>Now we have buttons with start and stop times in seconds. The "countdown.mp3" MP3 file consists of a number being spoken every 2 seconds, the idea being that we play back that number when the corresponding button is pressed.</p> <p>Let's add some JavaScript to make this work:</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>const myAudio = document.getElementById("myAudio"); const buttons = document.getElementsByTagName("button"); let stopTime = 0; for (const button of buttons) { button.addEventListener( "click", () => { myAudio.currentTime = button.getAttribute("data-start"); stopTime = button.getAttribute("data-stop"); myAudio.play(); }, false, ); } myAudio.addEventListener( "timeupdate", () => { if (myAudio.currentTime > stopTime) { myAudio.pause(); } }, false, ); </code></pre></div> <div class="notecard note"> <p><strong>Note:</strong> You can <a href="https://jsfiddle.net/59vwaame/" class="external" target="_blank">try out our audio sprite player live</a> on JSFiddle.</p> </div> <div class="notecard note"> <p><strong>Note:</strong> On mobile we may need to trigger this code from a user-initiated event such as a start button being pressed, as described above.</p> </div> <div class="notecard note"> <p><strong>Note:</strong> Watch out for bit rates. Encoding your audio at lower bit rates means smaller file sizes but lower seeking accuracy.</p> </div></div></section><section aria-labelledby="background_music"><h3 id="background_music"><a href="#background_music">Background music</a></h3><div class="section-content"><p>Music in games can have a powerful emotional effect. You can mix and match various music samples and assuming you can control the volume of your audio element you could cross-fade different musical pieces. Using the <a href="/en-US/docs/Web/API/HTMLMediaElement/playbackRate"><code>playbackRate()</code></a> method you can even adjust the speed of your music without affecting the pitch, to sync it up better with the action.</p> <p>All this is possible using the standard <a href="/en-US/docs/Web/HTML/Element/audio"><code><audio></code></a> element and associated <a href="/en-US/docs/Web/API/HTMLMediaElement"><code>HTMLMediaElement</code></a>, but it becomes much easier and more flexible with the more advanced <a href="/en-US/docs/Web/API/Web_Audio_API">Web Audio API</a>. Let's look at this next.</p></div></section><section aria-labelledby="web_audio_api_for_games"><h3 id="web_audio_api_for_games"><a href="#web_audio_api_for_games">Web Audio API for games</a></h3><div class="section-content"><p>The Web Audio API is supported across all modern desktop and mobile browsers, except for Opera Mini. With that in mind, it's an acceptable approach for many situations to use the Web Audio API (see the <a href="https://caniuse.com/#feat=audio-api" class="external" target="_blank">Can I use Web Audio API page</a> for more on browser compatibility). The Web Audio API is an advanced audio JavaScript API that is ideal for game audio. Developers can generate audio and manipulate audio samples as well as positioning sound in 3D game space.</p> <p>A feasible cross-browser strategy would be to provide basic audio using the standard <code><audio></code> element and, where supported, enhance the experience using the Web Audio API.</p> <div class="notecard note"> <p><strong>Note:</strong> Significantly, iOS Safari now supports the Web Audio API, which means it's now possible to write web-based games with native-quality audio for iOS.</p> </div> <p>As the Web Audio API allows precise timing and control of audio playback, we can use it to play samples at specific moments, which is a crucial immersive aspect of gaming. You want those explosions to be accompanied by a thundering boom, not followed by one, after all.</p></div></section><section aria-labelledby="background_music_with_the_web_audio_api"><h3 id="background_music_with_the_web_audio_api"><a href="#background_music_with_the_web_audio_api">Background music with the Web Audio API</a></h3><div class="section-content"><p>Although we can use the <code><audio></code> element to deliver linear background music that doesn't change in reaction to the game environment, the Web Audio API is ideal for implementing a more dynamic musical experience. You may want music to change depending on whether you are trying to build suspense or encourage the player in some way. Music is an important part of the gaming experience and depending on the type of game you are making you may wish to invest significant effort into getting it right.</p> <p>One way you can make your music soundtrack more dynamic is by splitting it up into component loops or tracks. This is often the way that musicians compose music anyway, and the Web Audio API is extremely good at keeping these parts in sync. Once you have the various tracks that make up your piece you can bring tracks in and out as appropriate.</p> <p>You can also apply filters or effects to music. Is your character in a cave? Increase the echo. Maybe you have underwater scenes, during which you could apply a filter that muffles the sound.</p> <p>Let's look at some Web Audio API techniques for dynamically adjusting music from its base tracks.</p></div></section><section aria-labelledby="loading_your_tracks"><h3 id="loading_your_tracks"><a href="#loading_your_tracks">Loading your tracks</a></h3><div class="section-content"><p>With the Web Audio API you can load separate tracks and loops individually using the <a href="/en-US/docs/Web/API/Fetch_API">Fetch API</a> or <a href="/en-US/docs/Web/API/XMLHttpRequest"><code>XMLHttpRequest</code></a>, which means you can load them synchronously or in parallel. Loading synchronously might mean parts of your music are ready earlier and you can start playing them while others load.</p> <p>Either way you may want to synchronize tracks or loops. The Web Audio API contains the notion of an internal clock that starts ticking the moment you create an audio context. You'll need to take account of the time between creating an audio context and when the first audio track starts playing. Recording this offset and querying the playing track's current time gives you enough information to synchronize separate pieces of audio.</p> <p>To see this in action, let's lay out some separate tracks:</p> <div class="code-example"><div class="example-header"><span class="language-name">html</span></div><pre class="brush: html notranslate"><code><section id="tracks"> <ul> <li data-loading="true"> <a href="leadguitar.mp3" class="track">Lead Guitar</a> <p class="loading-text">Loading…</p> <button data-playing="false" aria-describedby="guitar-play-label"> <span id="guitar-play-label">Play</span> </button> </li> <li data-loading="true"> <a href="bassguitar.mp3" class="track">Bass Guitar</a> <p class="loading-text">Loading…</p> <button data-playing="false" aria-describedby="bass-play-label"> <span id="bass-play-label">Play</span> </button> </li> <li data-loading="true"> <a href="drums.mp3" class="track">Drums</a> <p class="loading-text">Loading…</p> <button data-playing="false" aria-describedby="drums-play-label"> <span id="drums-play-label">Play</span> </button> </li> <li data-loading="true"> <a href="horns.mp3" class="track">Horns</a> <p class="loading-text">Loading…</p> <button data-playing="false" aria-describedby="horns-play-label"> <span id="horns-play-label">Play</span> </button> </li> <li data-loading="true"> <a href="clav.mp3" class="track">Clavi</a> <p class="loading-text">Loading…</p> <button data-playing="false" aria-describedby="clavi-play-label"> <span id="clavi-play-label">Play</span> </button> </li> </ul> <p class="sourced"> All tracks sourced from <a href="https://jplayer.org/">jplayer.org</a> </p> </section> </code></pre></div> <p>All of these tracks are the same tempo and are designed to be synchronized with each other, so we need to make sure they are loaded and available to the API <em>before</em> we are able to play them. We can do this with JavaScript's <a href="/en-US/docs/Web/JavaScript/Reference/Statements/async_function"><code>async</code></a>/<a href="/en-US/docs/Web/JavaScript/Reference/Operators/await"><code>await</code></a> functionality.</p> <p>Once they are available to play, we need to make sure they start at the correct point that other tracks might be playing at, so they sync up.</p> <p>Let's create our audio context:</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>const audioCtx = new AudioContext(); </code></pre></div> <p>Now let's select all the <a href="/en-US/docs/Web/HTML/Element/li"><code><li></code></a> elements; later we can harness these elements to give us access to the track file path and each individual play button.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>const trackEls = document.querySelectorAll("li"); </code></pre></div> <p>We want to make sure each file has loaded and been decoded into a buffer before we use it, so let's create an <code>async</code> function to allow us to do this:</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>async function getFile(filepath) { const response = await fetch(filepath); const arrayBuffer = await response.arrayBuffer(); const audioBuffer = await audioCtx.decodeAudioData(arrayBuffer); return audioBuffer; } </code></pre></div> <p>We can then use the <code>await</code> operator when calling this function, which ensures that we can run subsequent code when it has finished executing.</p> <p>Let's create another <code>async</code> function to set up the sample — we can combine the two async functions in a nice promise pattern to perform further actions when each file is loaded and buffered:</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>async function loadFile(filePath) { const track = await getFile(filePath); return track; } </code></pre></div> <p>Let's also create a <code>playTrack()</code> function, which we can call once a file has been fetched. We need an offset here, so if we have started one file playing, we have a record of how far through to start another file.</p> <p><code>start()</code> takes two optional parameters. The first is when to commence playback and the second is where, which is our offset.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>let offset = 0; function playTrack(audioBuffer) { const trackSource = audioCtx.createBufferSource(); trackSource.buffer = audioBuffer; trackSource.connect(audioCtx.destination); if (offset === 0) { trackSource.start(); offset = audioCtx.currentTime; } else { trackSource.start(0, audioCtx.currentTime - offset); } return trackSource; } </code></pre></div> <p>Finally, let's loop over our <code><li></code> elements, grab the correct file for each one and then allow playback by hiding the "loading" text and displaying the play button:</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>trackEls.forEach((el, i) => { // Get children const anchor = el.querySelector("a"); const loadText = el.querySelector("p"); const playButton = el.querySelector("button"); // Load file loadFile(anchor.href).then((track) => { // Set loading to false el.dataset.loading = "false"; // Hide loading text loadText.style.display = "none"; // Show button playButton.style.display = "inline-block"; // Allow play on click playButton.addEventListener("click", () => { // Check if context is in suspended state (autoplay policy) if (audioCtx.state === "suspended") { audioCtx.resume(); } playTrack(track); playButton.dataset.playing = true; }); }); }); </code></pre></div> <div class="notecard note"> <p><strong>Note:</strong> You can <a href="https://mdn.github.io/webaudio-examples/multi-track/" class="external" target="_blank">see this demo in action here</a> and <a href="https://github.com/mdn/webaudio-examples/tree/main/multi-track" class="external" target="_blank">view the source code here</a>.</p> </div> <p>In the context of your game world you may have loops and samples that are played in different circumstances, and it can be useful to be able to synchronize with other tracks for a more seamless experience.</p> <div class="notecard note"> <p><strong>Note:</strong> This example does not wait for the beat to end before introducing the next piece; we could do this if we knew the BPM (Beats Per Minute) of the tracks.</p> </div> <p>You may find that the introduction of a new track sounds more natural if it comes in on the beat/bar/phrase or whatever units you want to chunk your background music into.</p> <p>To do this before playing the track you want to sync, you should calculate how long it is until the start of the next beat/bar etc.</p> <p>Here's a bit of code that given a tempo (the time in seconds of your beat/bar) will calculate how long to wait until you play the next part — you feed the resulting value to the <code>start()</code> function with the first parameter, which takes the absolute time of when that playback should commence. Note the second parameter (where to start playing from in the new track) is relative:</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>if (offset === 0) { source.start(); offset = context.currentTime; } else { const relativeTime = context.currentTime - offset; const beats = relativeTime / tempo; const remainder = beats - Math.floor(beats); const delay = tempo - remainder * tempo; source.start(context.currentTime + delay, relativeTime + delay); } </code></pre></div> <div class="notecard note"> <p><strong>Note:</strong> You can <a href="https://jsfiddle.net/c87z11jj/2/" class="external" target="_blank">try our wait calculator code</a> here, on JSFiddle (I've synched to the bar in this case).</p> </div> <div class="notecard note"> <p><strong>Note:</strong> If the first parameter is 0 or less than the context <code>currentTime</code>, playback will commence immediately.</p> </div></div></section><section aria-labelledby="positional_audio"><h3 id="positional_audio"><a href="#positional_audio">Positional audio</a></h3><div class="section-content"><p>Positional audio can be an important technique in making audio a key part of an immersive gaming experience. The Web Audio API not only enables us to position a number of audio sources in three-dimensional space but it can also allow us to apply filters that make that audio appear more realistic.</p> <p>The <a href="/en-US/docs/Web/API/PannerNode"><code>pannerNode</code></a> harnesses the positional capabilities of the Web Audio API so we can relate further information about the game world to the player. There's a <a href="/en-US/docs/Web/API/Web_Audio_API/Web_audio_spatialization_basics">tutorial here</a> to help understand the <code>pannerNode</code> in better detail.</p> <p>We can relate:</p> <ul> <li>The position of objects</li> <li>The direction and movement of objects</li> <li>The environment (cavernous, underwater, etc.)</li> </ul> <p>This is especially useful in a three-dimensional environment rendered using WebGL, where the Web Audio API makes it possible to tie audio to the objects and viewpoints.</p></div></section><section aria-labelledby="see_also"><h2 id="see_also"><a href="#see_also">See also</a></h2><div class="section-content"><ul> <li><a href="/en-US/docs/Web/API/Web_Audio_API">Web Audio API on MDN</a></li> <li><a href="/en-US/docs/Web/HTML/Element/audio"><code><audio></code> on MDN</a></li> <li><a href="https://hacks.mozilla.org/2013/10/songs-of-diridum-pushing-the-web-audio-api-to-its-limits/" class="external" target="_blank">Songs of Diridum: Pushing the Web Audio API to Its Limits</a></li> <li><a href="https://pupunzi.open-lab.com/2013/03/13/making-html5-audio-actually-work-on-mobile/" class="external" target="_blank">Making HTML5 Audio Actually Work on Mobile</a></li> <li><a href="https://remysharp.com/2010/12/23/audio-sprites/" class="external" target="_blank">Audio Sprites (and fixes for iOS)</a></li> </ul></div></section></article><aside class="article-footer"><div class="article-footer-inner"><div class="svg-container"><svg xmlns="http://www.w3.org/2000/svg" width="162" height="162" viewBox="0 0 162 162" fill="none" role="none"><mask id="b" fill="#fff"><path d="M97.203 47.04c8.113-7.886 18.004-13.871 28.906-17.492a78 78 0 0 1 33.969-3.39c11.443 1.39 22.401 5.295 32.024 11.411s17.656 14.28 23.476 23.86c5.819 9.579 9.269 20.318 10.083 31.385a69.85 69.85 0 0 1-5.387 32.44c-4.358 10.272-11.115 19.443-19.747 26.801-8.632 7.359-18.908 12.709-30.034 15.637l-6.17-21.698c7.666-2.017 14.746-5.703 20.694-10.773 5.948-5.071 10.603-11.389 13.606-18.467a48.14 48.14 0 0 0 3.712-22.352c-.561-7.625-2.938-15.025-6.948-21.625s-9.544-12.226-16.175-16.44-14.181-6.904-22.065-7.863a53.75 53.75 0 0 0-23.405 2.336c-7.513 2.495-14.327 6.62-19.918 12.053z"></path></mask><path stroke="url(#a)" stroke-dasharray="6, 6" stroke-width="2" d="M97.203 47.04c8.113-7.886 18.004-13.871 28.906-17.492a78 78 0 0 1 33.969-3.39c11.443 1.39 22.401 5.295 32.024 11.411s17.656 14.28 23.476 23.86c5.819 9.579 9.269 20.318 10.083 31.385a69.85 69.85 0 0 1-5.387 32.44c-4.358 10.272-11.115 19.443-19.747 26.801-8.632 7.359-18.908 12.709-30.034 15.637l-6.17-21.698c7.666-2.017 14.746-5.703 20.694-10.773 5.948-5.071 10.603-11.389 13.606-18.467a48.14 48.14 0 0 0 3.712-22.352c-.561-7.625-2.938-15.025-6.948-21.625s-9.544-12.226-16.175-16.44-14.181-6.904-22.065-7.863a53.75 53.75 0 0 0-23.405 2.336c-7.513 2.495-14.327 6.62-19.918 12.053z" mask="url(#b)" style="stroke:url(#a)" transform="translate(-63.992 -25.587)"></path><ellipse cx="8.066" cy="111.597" fill="var(--background-tertiary)" rx="53.677" ry="53.699" transform="matrix(.71707 -.697 .7243 .6895 0 0)"></ellipse><g clip-path="url(#c)" transform="translate(-63.992 -25.587)"><path fill="#9abff5" d="m144.256 137.379 32.906 12.434a4.41 4.41 0 0 1 2.559 5.667l-9.326 24.679a4.41 4.41 0 0 1-5.667 2.559l-8.226-3.108-2.332 6.17c-.466 1.233-.375 1.883-1.609 1.417l-2.253-.527c-.411-.155-.95-.594-1.206-1.161l-4.734-10.484-12.545-4.741a4.41 4.41 0 0 1-2.559-5.667l9.325-24.679a4.41 4.41 0 0 1 5.667-2.559m9.961 29.617 8.227 3.108 3.264-8.638-.498-6.768-4.113-1.555.548 7.258-4.319-1.632zm-12.339-4.663 8.226 3.108 3.264-8.637-.498-6.769-4.113-1.554.548 7.257-4.319-1.632z"></path></g><g clip-path="url(#d)" transform="translate(-63.992 -25.587)"><path fill="#81b0f3" d="M135.35 60.136 86.67 41.654c-3.346-1.27-7.124.428-8.394 3.775L64.414 81.938c-1.27 3.347.428 7.125 3.774 8.395l12.17 4.62-3.465 9.128c-.693 1.826-1.432 2.457.394 3.15l3.014 1.625c.609.231 1.637.274 2.477-.104l15.53-6.983 18.56 7.047c3.346 1.27 7.124-.428 8.395-3.775l13.862-36.51c1.27-3.346-.428-7.124-3.775-8.395M95.261 83.207l-12.17-4.62 4.852-12.779 7.19-7.017 6.085 2.31-7.725 7.51 6.389 2.426zm18.255 6.93-12.17-4.62 4.852-12.778 7.189-7.017 6.085 2.31-7.725 7.51 6.39 2.426z"></path></g><defs><clipPath id="c"><path fill="#fff" d="m198.638 146.586-65.056-24.583-24.583 65.057 65.056 24.582z"></path></clipPath><clipPath id="d"><path fill="#fff" d="m66.438 14.055 96.242 36.54-36.54 96.243-96.243-36.54z"></path></clipPath><linearGradient id="a" x1="97.203" x2="199.995" y1="47.04" y2="152.793" gradientUnits="userSpaceOnUse"><stop stop-color="#086DFC"></stop><stop offset="0.246" stop-color="#2C81FA"></stop><stop offset="0.516" stop-color="#5497F8"></stop><stop offset="0.821" stop-color="#80B0F6"></stop><stop offset="1" stop-color="#9ABFF5"></stop></linearGradient></defs></svg></div><h2>Help improve MDN</h2><fieldset class="feedback"><label>Was this page helpful to you?</label><div class="button-container"><button type="button" class="button primary has-icon yes"><span class="button-wrap"><span class="icon icon-thumbs-up "></span>Yes</span></button><button type="button" class="button primary has-icon no"><span class="button-wrap"><span class="icon icon-thumbs-down "></span>No</span></button></div></fieldset><a class="contribute" href="https://github.com/mdn/content/blob/main/CONTRIBUTING.md" title="This will take you to our contribution guidelines on GitHub." target="_blank" rel="noopener noreferrer">Learn how to contribute</a>.<p class="last-modified-date">This page was last modified on<!-- --> <time dateTime="2024-10-25T00:08:46.000Z">Oct 25, 2024</time> by<!-- --> <a href="/en-US/docs/Games/Techniques/Audio_for_Web_Games/contributors.txt" rel="nofollow">MDN contributors</a>.</p><div id="on-github" class="on-github"><a href="https://github.com/mdn/content/blob/main/files/en-us/games/techniques/audio_for_web_games/index.md?plain=1" title="Folder: en-us/games/techniques/audio_for_web_games (Opens in a new tab)" target="_blank" rel="noopener noreferrer">View this page on GitHub</a> <!-- -->•<!-- --> <a href="https://github.com/mdn/content/issues/new?template=page-report.yml&mdn-url=https%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FGames%2FTechniques%2FAudio_for_Web_Games&metadata=%3C%21--+Do+not+make+changes+below+this+line+--%3E%0A%3Cdetails%3E%0A%3Csummary%3EPage+report+details%3C%2Fsummary%3E%0A%0A*+Folder%3A+%60en-us%2Fgames%2Ftechniques%2Faudio_for_web_games%60%0A*+MDN+URL%3A+https%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FGames%2FTechniques%2FAudio_for_Web_Games%0A*+GitHub+URL%3A+https%3A%2F%2Fgithub.com%2Fmdn%2Fcontent%2Fblob%2Fmain%2Ffiles%2Fen-us%2Fgames%2Ftechniques%2Faudio_for_web_games%2Findex.md%0A*+Last+commit%3A+https%3A%2F%2Fgithub.com%2Fmdn%2Fcontent%2Fcommit%2Fbaac7f2a43813a7930ff97b11d9c38b413f97c78%0A*+Document+last+modified%3A+2024-10-25T00%3A08%3A46.000Z%0A%0A%3C%2Fdetails%3E" title="This will take you to GitHub to file a new issue." target="_blank" rel="noopener noreferrer">Report a problem with this content</a></div></div></aside></main></div></div><footer id="nav-footer" class="page-footer"><div class="page-footer-grid"><div class="page-footer-logo-col"><a href="/" class="mdn-footer-logo" aria-label="MDN homepage"><svg width="48" height="17" viewBox="0 0 48 17" fill="none" xmlns="http://www.w3.org/2000/svg"><title id="mdn-footer-logo-svg">MDN logo</title><path d="M20.04 16.512H15.504V10.416C15.504 9.488 15.344 8.824 15.024 8.424C14.72 8.024 14.264 7.824 13.656 7.824C12.92 7.824 12.384 8.064 12.048 8.544C11.728 9.024 11.568 9.64 11.568 10.392V14.184H13.008V16.512H8.472V10.416C8.472 9.488 8.312 8.824 7.992 8.424C7.688 8.024 7.232 7.824 6.624 7.824C5.872 7.824 5.336 8.064 5.016 8.544C4.696 9.024 4.536 9.64 4.536 10.392V14.184H6.6V16.512H0V14.184H1.44V8.04H0.024V5.688H4.536V7.32C5.224 6.088 6.32 5.472 7.824 5.472C8.608 5.472 9.328 5.664 9.984 6.048C10.64 6.432 11.096 7.016 11.352 7.8C11.992 6.248 13.168 5.472 14.88 5.472C15.856 5.472 16.72 5.776 17.472 6.384C18.224 6.992 18.6 7.936 18.6 9.216V14.184H20.04V16.512Z" fill="currentColor"></path><path d="M33.6714 16.512H29.1354V14.496C28.8314 15.12 28.3834 15.656 27.7914 16.104C27.1994 16.536 26.4154 16.752 25.4394 16.752C24.0154 16.752 22.8954 16.264 22.0794 15.288C21.2634 14.312 20.8554 12.984 20.8554 11.304C20.8554 9.688 21.2554 8.312 22.0554 7.176C22.8554 6.04 24.0634 5.472 25.6794 5.472C26.5594 5.472 27.2794 5.648 27.8394 6C28.3994 6.352 28.8314 6.8 29.1354 7.344V2.352H26.9754V0H32.2314V14.184H33.6714V16.512ZM29.1354 11.04V10.776C29.1354 9.88 28.8954 9.184 28.4154 8.688C27.9514 8.176 27.3674 7.92 26.6634 7.92C25.9754 7.92 25.3674 8.176 24.8394 8.688C24.3274 9.2 24.0714 10.008 24.0714 11.112C24.0714 12.152 24.3114 12.944 24.7914 13.488C25.2714 14.032 25.8394 14.304 26.4954 14.304C27.3114 14.304 27.9514 13.96 28.4154 13.272C28.8954 12.584 29.1354 11.84 29.1354 11.04Z" fill="currentColor"></path><path d="M47.9589 16.512H41.9829V14.184H43.4229V10.416C43.4229 9.488 43.2629 8.824 42.9429 8.424C42.6389 8.024 42.1829 7.824 41.5749 7.824C40.8389 7.824 40.2709 8.056 39.8709 8.52C39.4709 8.968 39.2629 9.56 39.2469 10.296V14.184H40.6869V16.512H34.7109V14.184H36.1509V8.04H34.5909V5.688H39.2469V7.344C39.9669 6.096 41.1269 5.472 42.7269 5.472C43.7509 5.472 44.6389 5.776 45.3909 6.384C46.1429 6.992 46.5189 7.936 46.5189 9.216V14.184H47.9589V16.512Z" fill="currentColor"></path></svg></a><p>Your blueprint for a better internet.</p><ul class="social-icons"><li><a href="https://mozilla.social/@mdn" target="_blank" rel="me noopener noreferrer"><span class="icon icon-mastodon"></span><span class="visually-hidden">MDN on Mastodon</span></a></li><li><a href="https://twitter.com/mozdevnet" target="_blank" rel="noopener noreferrer"><span class="icon icon-twitter-x"></span><span class="visually-hidden">MDN on X (formerly Twitter)</span></a></li><li><a href="https://github.com/mdn/" target="_blank" rel="noopener noreferrer"><span class="icon icon-github-mark-small"></span><span class="visually-hidden">MDN on GitHub</span></a></li><li><a href="/en-US/blog/rss.xml" target="_blank"><span class="icon icon-feed"></span><span class="visually-hidden">MDN Blog RSS Feed</span></a></li></ul></div><div class="page-footer-nav-col-1"><h2 class="footer-nav-heading">MDN</h2><ul class="footer-nav-list"><li class="footer-nav-item"><a href="/en-US/about">About</a></li><li class="footer-nav-item"><a href="/en-US/blog/">Blog</a></li><li class="footer-nav-item"><a href="https://www.mozilla.org/en-US/careers/listings/?team=ProdOps" target="_blank" rel="noopener noreferrer">Careers</a></li><li class="footer-nav-item"><a href="/en-US/advertising">Advertise with us</a></li></ul></div><div class="page-footer-nav-col-2"><h2 class="footer-nav-heading">Support</h2><ul class="footer-nav-list"><li class="footer-nav-item"><a class="footer-nav-link" href="https://support.mozilla.org/products/mdn-plus">Product help</a></li><li class="footer-nav-item"><a class="footer-nav-link" href="/en-US/docs/MDN/Community/Issues">Report an issue</a></li></ul></div><div class="page-footer-nav-col-3"><h2 class="footer-nav-heading">Our communities</h2><ul class="footer-nav-list"><li class="footer-nav-item"><a class="footer-nav-link" href="/en-US/community">MDN Community</a></li><li class="footer-nav-item"><a class="footer-nav-link" href="https://discourse.mozilla.org/c/mdn/236" target="_blank" rel="noopener noreferrer">MDN Forum</a></li><li class="footer-nav-item"><a class="footer-nav-link" href="/discord" target="_blank" rel="noopener noreferrer">MDN Chat</a></li></ul></div><div class="page-footer-nav-col-4"><h2 class="footer-nav-heading">Developers</h2><ul class="footer-nav-list"><li class="footer-nav-item"><a class="footer-nav-link" href="/en-US/docs/Web">Web Technologies</a></li><li class="footer-nav-item"><a class="footer-nav-link" href="/en-US/docs/Learn">Learn Web Development</a></li><li class="footer-nav-item"><a class="footer-nav-link" href="/en-US/plus">MDN Plus</a></li><li class="footer-nav-item"><a href="https://hacks.mozilla.org/" target="_blank" rel="noopener noreferrer">Hacks Blog</a></li></ul></div><div class="page-footer-moz"><a href="https://www.mozilla.org/" class="footer-moz-logo-link" target="_blank" rel="noopener noreferrer"><svg width="112" height="32" fill="none" xmlns="http://www.w3.org/2000/svg"><title id="mozilla-footer-logo-svg">Mozilla logo</title><path d="M41.753 14.218c-2.048 0-3.324 1.522-3.324 4.157 0 2.423 1.119 4.286 3.29 4.286 2.082 0 3.447-1.678 3.447-4.347 0-2.826-1.522-4.096-3.413-4.096Zm54.89 7.044c0 .901.437 1.618 1.645 1.618 1.427 0 2.949-1.024 3.044-3.352-.649-.095-1.365-.185-2.02-.185-1.426-.005-2.668.397-2.668 1.92Z" fill="currentColor"></path><path d="M0 0v32h111.908V0H0Zm32.56 25.426h-5.87v-7.884c0-2.423-.806-3.352-2.39-3.352-1.924 0-2.702 1.365-2.702 3.324v4.868h1.864v3.044h-5.864v-7.884c0-2.423-.806-3.352-2.39-3.352-1.924 0-2.702 1.365-2.702 3.324v4.868h2.669v3.044H6.642v-3.044h1.863v-7.918H6.642V11.42h5.864v2.11c.839-1.489 2.3-2.39 4.252-2.39 2.02 0 3.878.963 4.566 3.01.778-1.862 2.361-3.01 4.566-3.01 2.512 0 4.812 1.522 4.812 4.84v6.402h1.863v3.044h-.005Zm9.036.307c-4.314 0-7.296-2.635-7.296-7.106 0-4.096 2.484-7.481 7.514-7.481s7.481 3.38 7.481 7.29c0 4.472-3.228 7.297-7.699 7.297Zm22.578-.307H51.942l-.403-2.11 7.7-8.846h-4.376l-.621 2.17-2.888-.313.498-4.907h12.294l.313 2.11-7.767 8.852h4.533l.654-2.172 3.167.308-.872 4.908Zm7.99 0h-4.191v-5.03h4.19v5.03Zm0-8.976h-4.191v-5.03h4.19v5.03Zm2.618 8.976 6.054-21.358h3.945l-6.054 21.358h-3.945Zm8.136 0 6.048-21.358h3.945l-6.054 21.358h-3.939Zm21.486.307c-1.863 0-2.887-1.085-3.072-2.792-.805 1.427-2.232 2.792-4.498 2.792-2.02 0-4.314-1.085-4.314-4.006 0-3.447 3.323-4.253 6.518-4.253.778 0 1.584.034 2.3.124v-.465c0-1.427-.034-3.133-2.3-3.133-.84 0-1.488.061-2.143.402l-.453 1.578-3.195-.34.549-3.224c2.45-.996 3.692-1.27 5.992-1.27 3.01 0 5.556 1.55 5.556 4.75v6.083c0 .805.314 1.085.963 1.085.184 0 .375-.034.587-.095l.034 2.11a5.432 5.432 0 0 1-2.524.654Z" fill="currentColor"></path></svg></a><ul class="footer-moz-list"><li class="footer-moz-item"><a href="https://www.mozilla.org/privacy/websites/" class="footer-moz-link" target="_blank" rel="noopener noreferrer">Website Privacy Notice</a></li><li class="footer-moz-item"><a href="https://www.mozilla.org/privacy/websites/#cookies" class="footer-moz-link" target="_blank" rel="noopener noreferrer">Cookies</a></li><li class="footer-moz-item"><a href="https://www.mozilla.org/about/legal/terms/mozilla" class="footer-moz-link" target="_blank" rel="noopener noreferrer">Legal</a></li><li class="footer-moz-item"><a href="https://www.mozilla.org/about/governance/policies/participation/" class="footer-moz-link" target="_blank" rel="noopener noreferrer">Community Participation Guidelines</a></li></ul></div><div class="page-footer-legal"><p id="license" class="page-footer-legal-text">Visit<!-- --> <a href="https://www.mozilla.org" target="_blank" rel="noopener noreferrer">Mozilla Corporation’s</a> <!-- -->not-for-profit parent, the<!-- --> <a target="_blank" rel="noopener noreferrer" href="https://foundation.mozilla.org/">Mozilla Foundation</a>.<br/>Portions of this content are ©1998–<!-- -->2024<!-- --> by individual mozilla.org contributors. Content available under<!-- --> <a href="/en-US/docs/MDN/Writing_guidelines/Attrib_copyright_license">a Creative Commons license</a>.</p></div></div></footer></div><script type="application/json" id="hydration">{"url":"/en-US/docs/Games/Techniques/Audio_for_Web_Games","doc":{"isMarkdown":true,"isTranslated":false,"isActive":true,"flaws":{},"title":"Audio for Web games","mdn_url":"/en-US/docs/Games/Techniques/Audio_for_Web_Games","locale":"en-US","native":"English (US)","sidebarHTML":"\n <ol>\n <li class=\"toggle\">\n <details>\n <summary>Introduction</summary>\n <ol>\n <li><a href=\"/en-US/docs/Games/Introduction\">Introduction</a></li>\n <li><a href=\"/en-US/docs/Games/Anatomy\">Anatomy</a></li>\n </ol>\n </details>\n </li>\n <li class=\"toggle\">\n <details>\n <summary>APIs for game development</summary>\n <ol>\n <li><a href=\"/en-US/docs/Web/API/Canvas_API\">Canvas</a></li>\n <li><a href=\"/en-US/docs/Web/CSS\">CSS</a></li>\n <li><a href=\"/en-US/docs/Web/API/Fullscreen_API\">Full screen</a></li>\n <li><a href=\"/en-US/docs/Web/API/Gamepad_API\">Gamepad</a></li>\n <li><a href=\"/en-US/docs/Web/API/IndexedDB_API\">IndexedDB</a></li>\n <li><a href=\"/en-US/docs/Web/JavaScript\">JavaScript</a></li>\n <li><a href=\"/en-US/docs/Web/API/Pointer_Lock_API\">Pointer Lock</a></li>\n <li><a href=\"/en-US/docs/Web/SVG\">SVG</a></li>\n <li><a href=\"/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray\">Typed Arrays</a></li>\n <li><a href=\"/en-US/docs/Web/API/Web_Audio_API\">Web Audio</a></li>\n <li><a href=\"/en-US/docs/Web/API/WebGL_API\">WebGL</a></li>\n <li><a href=\"/en-US/docs/Web/API/WebRTC_API\">WebRTC</a></li>\n <li><a href=\"/en-US/docs/Web/API/WebSockets_API\">WebSockets</a></li>\n <li><a href=\"/en-US/docs/Web/API/WebVR_API\">WebVR</a></li>\n <li><a href=\"/en-US/docs/Web/API/Web_Workers_API\">Web Workers</a></li>\n <li><a href=\"/en-US/docs/Web/API/XMLHttpRequest\">XMLHttpRequest</a></li>\n </ol>\n </details>\n </li>\n <li class=\"toggle\">\n <details open=\"\">\n <summary>Techniques</summary>\n <ol>\n <li><a href=\"/en-US/docs/Games/Techniques/Async_scripts\">Using async scripts for asm.js</a></li>\n <li><a href=\"/en-US/docs/Web/Performance/Optimizing_startup_performance\">Optimizing startup performance</a></li>\n <li><a href=\"/en-US/docs/Games/Techniques/WebRTC_data_channels\">Using WebRTC peer-to-peer data channels</a></li>\n <li><em><a href=\"/en-US/docs/Games/Techniques/Audio_for_Web_Games\" aria-current=\"page\">Audio for Web Games</a></em></li>\n <li><a href=\"/en-US/docs/Games/Techniques/2D_collision_detection\">2D collision detection</a></li>\n <li><a href=\"/en-US/docs/Games/Techniques/Tilemaps\">Tiles and tilemaps overview</a></li>\n </ol>\n </details>\n </li>\n <li class=\"toggle\">\n <details>\n <summary>3D games on the Web</summary>\n <ol>\n <li><a href=\"/en-US/docs/Games/Techniques/3D_on_the_web\">3D games on the Web overview</a></li>\n <li><a href=\"/en-US/docs/Games/Techniques/3D_on_the_web/Basic_theory\">Explaining basic 3D theory</a></li>\n <li><a href=\"/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_A-Frame\">Building up a basic demo with A-Frame</a></li>\n <li><a href=\"/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_Babylon.js\">Building up a basic demo with Babylon.js</a></li>\n <li><a href=\"/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas\">Building up a basic demo with PlayCanvas</a></li>\n <li><a href=\"/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_Three.js\">Building up a basic demo with Three.js</a></li>\n <li><a href=\"/en-US/docs/Games/Techniques/3D_on_the_web/WebXR\">WebXR</a></li>\n <li><a href=\"/en-US/docs/Games/Techniques/3D_collision_detection\">3D collision detection</a></li>\n <li><a href=\"/en-US/docs/Games/Techniques/3D_collision_detection/Bounding_volume_collision_detection_with_THREE.js\">Bounding volume collision detection with THREE.js</a></li>\n </ol>\n </details>\n </li>\n <li class=\"toggle\">\n <details>\n <summary>Implementing game control mechanisms</summary>\n <ol>\n <li><a href=\"/en-US/docs/Games/Techniques/Control_mechanisms\">Control mechanisms</a></li>\n <li><a href=\"/en-US/docs/Games/Techniques/Control_mechanisms/Mobile_touch\">Mobile touch</a></li>\n <li><a href=\"/en-US/docs/Games/Techniques/Control_mechanisms/Desktop_with_mouse_and_keyboard\">Desktop with mouse and keyboard</a></li>\n <li><a href=\"/en-US/docs/Games/Techniques/Control_mechanisms/Desktop_with_gamepad\">Desktop with gamepad</a></li>\n <li><a href=\"/en-US/docs/Games/Techniques/Control_mechanisms/Other\">Other</a></li>\n </ol>\n </details>\n </li>\n <li class=\"toggle\">\n <details>\n <summary>Tutorials</summary>\n <ol>\n <li><a href=\"/en-US/docs/Games/Tutorials/2D_Breakout_game_pure_JavaScript\">2D breakout game using pure JavaScript</a></li>\n <li><a href=\"/en-US/docs/Games/Tutorials/2D_breakout_game_Phaser\">2D breakout game using Phaser</a></li>\n <li><a href=\"/en-US/docs/Games/Tutorials/HTML5_Gamedev_Phaser_Device_Orientation\">2D maze_game with device orientation</a></li>\n <li><a href=\"https://mozdevs.github.io/html5-games-workshop/en/guides/platformer/start-here/\">2D platform game using Phaser</a></li>\n </ol>\n </details>\n </li>\n <li class=\"toggle\">\n <details>\n <summary>Publishing games</summary>\n <ol>\n <li><a href=\"/en-US/docs/Games/Publishing_games\">Publishing games overview</a></li>\n <li><a href=\"/en-US/docs/Games/Publishing_games/Game_distribution\">Game distribution</a></li>\n <li><a href=\"/en-US/docs/Games/Publishing_games/Game_promotion\">Game promotion</a></li>\n <li><a href=\"/en-US/docs/Games/Publishing_games/Game_monetization\">Game monetization</a></li>\n </ol>\n </details>\n </li>\n </ol>\n","sidebarMacro":"GamesSidebar","body":[{"type":"prose","value":{"id":null,"title":null,"isH3":false,"content":"<p>Audio is an important part of any game; it adds feedback and atmosphere. Web-based audio is maturing fast, but there are still many browser differences to navigate. We often need to decide which audio parts are essential to our games' experience and which are nice to have but not essential, and devise a strategy accordingly. This article provides a detailed guide to implementing audio for web games, looking at what works currently across as wide a range of platforms as possible.</p>"}},{"type":"prose","value":{"id":"mobile_audio_caveats","title":"Mobile audio caveats","isH3":false,"content":"<p>By far the most difficult platforms to provide web audio support for are mobile platforms. Unfortunately these are also the platforms that people often use to play games. There are a couple of differences between desktop and mobile browsers that may have caused browser vendors to make choices that can make web audio difficult for game developers to work with. Let's look at these now.</p>"}},{"type":"prose","value":{"id":"autoplay","title":"Autoplay","isH3":true,"content":"<p>Browser autoplay policy now affects desktop <em>and</em> mobile browsers. There is further information about it <a href=\"https://developer.chrome.com/blog/autoplay/\" class=\"external\" target=\"_blank\">here from the Google Developers site</a>.</p>\n<p>It is worth noting that autoplay with sound is allowed if:</p>\n<ul>\n <li>the User has interacted with the domain.</li>\n <li>on mobile the user has <a href=\"/en-US/docs/Web/Progressive_web_apps/Guides/Making_PWAs_installable\">made the application installable</a>.</li>\n</ul>\n<p>Many browsers will ignore any requests made by your game to automatically play audio; instead playback for audio needs to be started by a user-initiated event, such as a click or tap. This means you will have to structure your audio playback to take account of that. This is usually mitigated against by loading the audio in advance and priming it on a user-initiated event.</p>\n<p>For more passive audio autoplay, for example background music that starts as soon as a game loads, one trick is to detect <em>any</em> user initiated event and start playback then. For other more active sounds that are to be used during the game we could consider priming them as soon as something like a <em>Start</em> button is pressed.</p>\n<p>To prime audio like this we want to play a part of it; for this reason it is useful to include a moment of silence at the end of your audio sample. Jumping to, playing, and then pausing that silence will mean we can now use JavaScript to play that file at arbitrary points. You can find out more about <a href=\"/en-US/docs/Web/API/Web_Audio_API/Best_practices#autoplay_policy\">best practices with the autoplay policy here</a>.</p>\n<div class=\"notecard note\">\n <p><strong>Note:</strong> Playing part of your file at zero volume could also work if the browser allows you to change volume (see below). Also note that playing and immediately pausing your audio does not guarantee that a small piece of audio won't be played.</p>\n</div>\n<div class=\"notecard note\">\n <p><strong>Note:</strong> Adding a web app to your mobile's homescreen may change its capabilities. In the case of autoplay on iOS, this appears to be the case currently. If possible, you should try your code on several devices and platforms to see how it works.</p>\n</div>"}},{"type":"prose","value":{"id":"volume","title":"Volume","isH3":true,"content":"<p>Programmatic volume control may be disabled in mobile browsers. The reason often given is that the user should be in control of the volume at the OS level and this shouldn't be overridden.</p>"}},{"type":"prose","value":{"id":"buffering_and_preloading","title":"Buffering and preloading","isH3":true,"content":"<p>Likely as an attempt to mitigate runaway mobile network data use, we also often find that buffering is disabled before playback has been initiated. Buffering is the process of the browser downloading the media in advance, which we often need to do to ensure smooth playback.</p>\n<p>The <a href=\"/en-US/docs/Web/API/HTMLMediaElement\"><code>HTMLMediaElement</code></a> interface comes with <a href=\"/en-US/docs/Web/API/HTMLMediaElement#instance_properties\">lots of properties</a> to help determine whether a track is in a state to be playable.</p>\n<div class=\"notecard note\">\n <p><strong>Note:</strong> In many ways the concept of buffering is an outdated one. As long as byte-range requests are accepted (which is the default behavior), we should be able to jump to a specific point in the audio without having to download the preceding content. However, preloading is still useful — without it, there would always need to be some client-server communication required before playing can commence.</p>\n</div>"}},{"type":"prose","value":{"id":"concurrent_audio_playback","title":"Concurrent audio playback","isH3":true,"content":"<p>A requirement of many games is the need to play more than one piece of audio at the same time; for example, there might be background music playing along with sound effects for various things happening in the game. Although the situation is soon going to get better with the adoption of the <a href=\"/en-US/docs/Web/API/Web_Audio_API\">Web Audio API</a>, the current most widely-supported method — using the vanilla <a href=\"/en-US/docs/Web/HTML/Element/audio\"><code><audio></code></a> element — leads to patchy results on mobile devices.</p>"}},{"type":"prose","value":{"id":"testing_and_support","title":"Testing and support","isH3":true,"content":"<p>Here's a table that shows what mobile platforms support the features talked about above.</p>\n<figure class=\"table-container\"><table class=\"standard-table\">\n <caption>Mobile support for web audio features</caption>\n <thead>\n <tr>\n <th scope=\"row\">Mobile browser</th>\n <th scope=\"col\">Version</th>\n <th scope=\"col\">Concurrent play</th>\n <th scope=\"col\">Autoplay</th>\n <th scope=\"col\">Volume adjusting</th>\n <th scope=\"col\">Preload</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th scope=\"row\">Chrome (Android)</th>\n <td>69+</td>\n <td>Y</td>\n <td>Y</td>\n <td>Y</td>\n <td>Y</td>\n </tr>\n <tr>\n <th scope=\"row\">Firefox (Android)</th>\n <td>62+</td>\n <td>Y</td>\n <td>Y</td>\n <td>Y</td>\n <td>Y</td>\n </tr>\n <tr>\n <th scope=\"row\">Edge Mobile</th>\n <td></td>\n <td>Y</td>\n <td>Y</td>\n <td>Y</td>\n <td>Y</td>\n </tr>\n <tr>\n <th scope=\"row\">Opera Mobile</th>\n <td>46+</td>\n <td>Y</td>\n <td>Y</td>\n <td>Y</td>\n <td>Y</td>\n </tr>\n <tr>\n <th scope=\"row\">Safari (iOS)</th>\n <td>7+</td>\n <td>Y/N*</td>\n <td>N</td>\n <td>N</td>\n <td>Y</td>\n </tr>\n <tr>\n <th scope=\"row\">Android Browser</th>\n <td>67+</td>\n <td>Y</td>\n <td>Y</td>\n <td>Y</td>\n <td>Y</td>\n </tr>\n </tbody>\n</table></figure>\n<p>There's a <a href=\"/en-US/docs/Web/API/HTMLMediaElement#browser_compatibility\">full compatibility chart for mobile and desktop HTMLMediaElement support here</a>.</p>\n<div class=\"notecard note\">\n <p><strong>Note:</strong> Concurrent audio playback is tested using our <a href=\"https://jsfiddle.net/dmkyaq0r/\" class=\"external\" target=\"_blank\">concurrent audio test example</a>, where we attempt to play three pieces of audio at the same time using the standard audio API.</p>\n</div>\n<div class=\"notecard note\">\n <p><strong>Note:</strong> Simple autoplay functionality is tested with our <a href=\"https://jsfiddle.net/vpdspp2b/\" class=\"external\" target=\"_blank\">autoplay test example</a>.</p>\n</div>\n<div class=\"notecard note\">\n <p><strong>Note:</strong> Volume changeability is tested with our <a href=\"https://jsfiddle.net/7ta12vw4/\" class=\"external\" target=\"_blank\">volume test example</a>.</p>\n</div>"}},{"type":"prose","value":{"id":"mobile_workarounds","title":"Mobile workarounds","isH3":false,"content":"<p>Although mobile browsers can present problems, there are ways to work around the issues detailed above.</p>"}},{"type":"prose","value":{"id":"audio_sprites","title":"Audio sprites","isH3":true,"content":"<p>Audio sprites borrow their name from <a href=\"/en-US/docs/Web/CSS/CSS_images/Implementing_image_sprites_in_CSS\">CSS sprites</a>, which is a visual technique for using CSS with a single graphic resource to break it into a series of sprites. We can apply the same principle to audio so that rather than having a bunch of small audio files that take time to load and play, we have one larger audio file containing all the smaller audio snippets we need. To play a specific sound from the file, we just use the known start and stop times for each audio sprite.</p>\n<p>The advantage is that we can prime one piece of audio and have our sprites ready to go. To do this we can just play and instantly pause the larger piece of audio. You'll also reduce the number of server requests and save bandwidth.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>const myAudio = document.createElement(\"audio\");\nmyAudio.src = \"my-sprite.mp3\";\nmyAudio.play();\nmyAudio.pause();\n</code></pre></div>\n<p>You'll need to sample the current time to know when to stop. If you space your individual sounds by at least 500ms then using the <code>timeUpdate</code> event (which fires every 250ms) should be sufficient. Your files may be slightly longer than they strictly need to be, but silence compresses well.</p>\n<p>Here's an example of an audio sprite player — first let's set up the user interface in HTML:</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">html</span></div><pre class=\"brush: html notranslate\"><code><audio id=\"myAudio\" src=\"http://jPlayer.org/tmp/countdown.mp3\"></audio>\n<button data-start=\"18\" data-stop=\"19\">0</button>\n<button data-start=\"16\" data-stop=\"17\">1</button>\n<button data-start=\"14\" data-stop=\"15\">2</button>\n<button data-start=\"12\" data-stop=\"13\">3</button>\n<button data-start=\"10\" data-stop=\"11\">4</button>\n<button data-start=\"8\" data-stop=\"9\">5</button>\n<button data-start=\"6\" data-stop=\"7\">6</button>\n<button data-start=\"4\" data-stop=\"5\">7</button>\n<button data-start=\"2\" data-stop=\"3\">8</button>\n<button data-start=\"0\" data-stop=\"1\">9</button>\n</code></pre></div>\n<p>Now we have buttons with start and stop times in seconds. The \"countdown.mp3\" MP3 file consists of a number being spoken every 2 seconds, the idea being that we play back that number when the corresponding button is pressed.</p>\n<p>Let's add some JavaScript to make this work:</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>const myAudio = document.getElementById(\"myAudio\");\nconst buttons = document.getElementsByTagName(\"button\");\nlet stopTime = 0;\n\nfor (const button of buttons) {\n button.addEventListener(\n \"click\",\n () => {\n myAudio.currentTime = button.getAttribute(\"data-start\");\n stopTime = button.getAttribute(\"data-stop\");\n myAudio.play();\n },\n false,\n );\n}\n\nmyAudio.addEventListener(\n \"timeupdate\",\n () => {\n if (myAudio.currentTime > stopTime) {\n myAudio.pause();\n }\n },\n false,\n);\n</code></pre></div>\n<div class=\"notecard note\">\n <p><strong>Note:</strong> You can <a href=\"https://jsfiddle.net/59vwaame/\" class=\"external\" target=\"_blank\">try out our audio sprite player live</a> on JSFiddle.</p>\n</div>\n<div class=\"notecard note\">\n <p><strong>Note:</strong> On mobile we may need to trigger this code from a user-initiated event such as a start button being pressed, as described above.</p>\n</div>\n<div class=\"notecard note\">\n <p><strong>Note:</strong> Watch out for bit rates. Encoding your audio at lower bit rates means smaller file sizes but lower seeking accuracy.</p>\n</div>"}},{"type":"prose","value":{"id":"background_music","title":"Background music","isH3":true,"content":"<p>Music in games can have a powerful emotional effect. You can mix and match various music samples and assuming you can control the volume of your audio element you could cross-fade different musical pieces. Using the <a href=\"/en-US/docs/Web/API/HTMLMediaElement/playbackRate\"><code>playbackRate()</code></a> method you can even adjust the speed of your music without affecting the pitch, to sync it up better with the action.</p>\n<p>All this is possible using the standard <a href=\"/en-US/docs/Web/HTML/Element/audio\"><code><audio></code></a> element and associated <a href=\"/en-US/docs/Web/API/HTMLMediaElement\"><code>HTMLMediaElement</code></a>, but it becomes much easier and more flexible with the more advanced <a href=\"/en-US/docs/Web/API/Web_Audio_API\">Web Audio API</a>. Let's look at this next.</p>"}},{"type":"prose","value":{"id":"web_audio_api_for_games","title":"Web Audio API for games","isH3":true,"content":"<p>The Web Audio API is supported across all modern desktop and mobile browsers, except for Opera Mini. With that in mind, it's an acceptable approach for many situations to use the Web Audio API (see the <a href=\"https://caniuse.com/#feat=audio-api\" class=\"external\" target=\"_blank\">Can I use Web Audio API page</a> for more on browser compatibility). The Web Audio API is an advanced audio JavaScript API that is ideal for game audio. Developers can generate audio and manipulate audio samples as well as positioning sound in 3D game space.</p>\n<p>A feasible cross-browser strategy would be to provide basic audio using the standard <code><audio></code> element and, where supported, enhance the experience using the Web Audio API.</p>\n<div class=\"notecard note\">\n <p><strong>Note:</strong> Significantly, iOS Safari now supports the Web Audio API, which means it's now possible to write web-based games with native-quality audio for iOS.</p>\n</div>\n<p>As the Web Audio API allows precise timing and control of audio playback, we can use it to play samples at specific moments, which is a crucial immersive aspect of gaming. You want those explosions to be accompanied by a thundering boom, not followed by one, after all.</p>"}},{"type":"prose","value":{"id":"background_music_with_the_web_audio_api","title":"Background music with the Web Audio API","isH3":true,"content":"<p>Although we can use the <code><audio></code> element to deliver linear background music that doesn't change in reaction to the game environment, the Web Audio API is ideal for implementing a more dynamic musical experience. You may want music to change depending on whether you are trying to build suspense or encourage the player in some way. Music is an important part of the gaming experience and depending on the type of game you are making you may wish to invest significant effort into getting it right.</p>\n<p>One way you can make your music soundtrack more dynamic is by splitting it up into component loops or tracks. This is often the way that musicians compose music anyway, and the Web Audio API is extremely good at keeping these parts in sync. Once you have the various tracks that make up your piece you can bring tracks in and out as appropriate.</p>\n<p>You can also apply filters or effects to music. Is your character in a cave? Increase the echo. Maybe you have underwater scenes, during which you could apply a filter that muffles the sound.</p>\n<p>Let's look at some Web Audio API techniques for dynamically adjusting music from its base tracks.</p>"}},{"type":"prose","value":{"id":"loading_your_tracks","title":"Loading your tracks","isH3":true,"content":"<p>With the Web Audio API you can load separate tracks and loops individually using the <a href=\"/en-US/docs/Web/API/Fetch_API\">Fetch API</a> or <a href=\"/en-US/docs/Web/API/XMLHttpRequest\"><code>XMLHttpRequest</code></a>, which means you can load them synchronously or in parallel. Loading synchronously might mean parts of your music are ready earlier and you can start playing them while others load.</p>\n<p>Either way you may want to synchronize tracks or loops. The Web Audio API contains the notion of an internal clock that starts ticking the moment you create an audio context. You'll need to take account of the time between creating an audio context and when the first audio track starts playing. Recording this offset and querying the playing track's current time gives you enough information to synchronize separate pieces of audio.</p>\n<p>To see this in action, let's lay out some separate tracks:</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">html</span></div><pre class=\"brush: html notranslate\"><code><section id=\"tracks\">\n <ul>\n <li data-loading=\"true\">\n <a href=\"leadguitar.mp3\" class=\"track\">Lead Guitar</a>\n <p class=\"loading-text\">Loading…</p>\n <button data-playing=\"false\" aria-describedby=\"guitar-play-label\">\n <span id=\"guitar-play-label\">Play</span>\n </button>\n </li>\n <li data-loading=\"true\">\n <a href=\"bassguitar.mp3\" class=\"track\">Bass Guitar</a>\n <p class=\"loading-text\">Loading…</p>\n <button data-playing=\"false\" aria-describedby=\"bass-play-label\">\n <span id=\"bass-play-label\">Play</span>\n </button>\n </li>\n <li data-loading=\"true\">\n <a href=\"drums.mp3\" class=\"track\">Drums</a>\n <p class=\"loading-text\">Loading…</p>\n <button data-playing=\"false\" aria-describedby=\"drums-play-label\">\n <span id=\"drums-play-label\">Play</span>\n </button>\n </li>\n <li data-loading=\"true\">\n <a href=\"horns.mp3\" class=\"track\">Horns</a>\n <p class=\"loading-text\">Loading…</p>\n <button data-playing=\"false\" aria-describedby=\"horns-play-label\">\n <span id=\"horns-play-label\">Play</span>\n </button>\n </li>\n <li data-loading=\"true\">\n <a href=\"clav.mp3\" class=\"track\">Clavi</a>\n <p class=\"loading-text\">Loading…</p>\n <button data-playing=\"false\" aria-describedby=\"clavi-play-label\">\n <span id=\"clavi-play-label\">Play</span>\n </button>\n </li>\n </ul>\n <p class=\"sourced\">\n All tracks sourced from <a href=\"https://jplayer.org/\">jplayer.org</a>\n </p>\n</section>\n</code></pre></div>\n<p>All of these tracks are the same tempo and are designed to be synchronized with each other, so we need to make sure they are loaded and available to the API <em>before</em> we are able to play them. We can do this with JavaScript's <a href=\"/en-US/docs/Web/JavaScript/Reference/Statements/async_function\"><code>async</code></a>/<a href=\"/en-US/docs/Web/JavaScript/Reference/Operators/await\"><code>await</code></a> functionality.</p>\n<p>Once they are available to play, we need to make sure they start at the correct point that other tracks might be playing at, so they sync up.</p>\n<p>Let's create our audio context:</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>const audioCtx = new AudioContext();\n</code></pre></div>\n<p>Now let's select all the <a href=\"/en-US/docs/Web/HTML/Element/li\"><code><li></code></a> elements; later we can harness these elements to give us access to the track file path and each individual play button.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>const trackEls = document.querySelectorAll(\"li\");\n</code></pre></div>\n<p>We want to make sure each file has loaded and been decoded into a buffer before we use it, so let's create an <code>async</code> function to allow us to do this:</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>async function getFile(filepath) {\n const response = await fetch(filepath);\n const arrayBuffer = await response.arrayBuffer();\n const audioBuffer = await audioCtx.decodeAudioData(arrayBuffer);\n return audioBuffer;\n}\n</code></pre></div>\n<p>We can then use the <code>await</code> operator when calling this function, which ensures that we can run subsequent code when it has finished executing.</p>\n<p>Let's create another <code>async</code> function to set up the sample — we can combine the two async functions in a nice promise pattern to perform further actions when each file is loaded and buffered:</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>async function loadFile(filePath) {\n const track = await getFile(filePath);\n return track;\n}\n</code></pre></div>\n<p>Let's also create a <code>playTrack()</code> function, which we can call once a file has been fetched. We need an offset here, so if we have started one file playing, we have a record of how far through to start another file.</p>\n<p><code>start()</code> takes two optional parameters. The first is when to commence playback and the second is where, which is our offset.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>let offset = 0;\n\nfunction playTrack(audioBuffer) {\n const trackSource = audioCtx.createBufferSource();\n trackSource.buffer = audioBuffer;\n trackSource.connect(audioCtx.destination);\n\n if (offset === 0) {\n trackSource.start();\n offset = audioCtx.currentTime;\n } else {\n trackSource.start(0, audioCtx.currentTime - offset);\n }\n\n return trackSource;\n}\n</code></pre></div>\n<p>Finally, let's loop over our <code><li></code> elements, grab the correct file for each one and then allow playback by hiding the \"loading\" text and displaying the play button:</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>trackEls.forEach((el, i) => {\n // Get children\n const anchor = el.querySelector(\"a\");\n const loadText = el.querySelector(\"p\");\n const playButton = el.querySelector(\"button\");\n\n // Load file\n loadFile(anchor.href).then((track) => {\n // Set loading to false\n el.dataset.loading = \"false\";\n\n // Hide loading text\n loadText.style.display = \"none\";\n\n // Show button\n playButton.style.display = \"inline-block\";\n\n // Allow play on click\n playButton.addEventListener(\"click\", () => {\n // Check if context is in suspended state (autoplay policy)\n if (audioCtx.state === \"suspended\") {\n audioCtx.resume();\n }\n\n playTrack(track);\n playButton.dataset.playing = true;\n });\n });\n});\n</code></pre></div>\n<div class=\"notecard note\">\n <p><strong>Note:</strong> You can <a href=\"https://mdn.github.io/webaudio-examples/multi-track/\" class=\"external\" target=\"_blank\">see this demo in action here</a> and <a href=\"https://github.com/mdn/webaudio-examples/tree/main/multi-track\" class=\"external\" target=\"_blank\">view the source code here</a>.</p>\n</div>\n<p>In the context of your game world you may have loops and samples that are played in different circumstances, and it can be useful to be able to synchronize with other tracks for a more seamless experience.</p>\n<div class=\"notecard note\">\n <p><strong>Note:</strong> This example does not wait for the beat to end before introducing the next piece; we could do this if we knew the BPM (Beats Per Minute) of the tracks.</p>\n</div>\n<p>You may find that the introduction of a new track sounds more natural if it comes in on the beat/bar/phrase or whatever units you want to chunk your background music into.</p>\n<p>To do this before playing the track you want to sync, you should calculate how long it is until the start of the next beat/bar etc.</p>\n<p>Here's a bit of code that given a tempo (the time in seconds of your beat/bar) will calculate how long to wait until you play the next part — you feed the resulting value to the <code>start()</code> function with the first parameter, which takes the absolute time of when that playback should commence. Note the second parameter (where to start playing from in the new track) is relative:</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>if (offset === 0) {\n source.start();\n offset = context.currentTime;\n} else {\n const relativeTime = context.currentTime - offset;\n const beats = relativeTime / tempo;\n const remainder = beats - Math.floor(beats);\n const delay = tempo - remainder * tempo;\n source.start(context.currentTime + delay, relativeTime + delay);\n}\n</code></pre></div>\n<div class=\"notecard note\">\n <p><strong>Note:</strong> You can <a href=\"https://jsfiddle.net/c87z11jj/2/\" class=\"external\" target=\"_blank\">try our wait calculator code</a> here, on JSFiddle (I've synched to the bar in this case).</p>\n</div>\n<div class=\"notecard note\">\n <p><strong>Note:</strong> If the first parameter is 0 or less than the context <code>currentTime</code>, playback will commence immediately.</p>\n</div>"}},{"type":"prose","value":{"id":"positional_audio","title":"Positional audio","isH3":true,"content":"<p>Positional audio can be an important technique in making audio a key part of an immersive gaming experience. The Web Audio API not only enables us to position a number of audio sources in three-dimensional space but it can also allow us to apply filters that make that audio appear more realistic.</p>\n<p>The <a href=\"/en-US/docs/Web/API/PannerNode\"><code>pannerNode</code></a> harnesses the positional capabilities of the Web Audio API so we can relate further information about the game world to the player. There's a <a href=\"/en-US/docs/Web/API/Web_Audio_API/Web_audio_spatialization_basics\">tutorial here</a> to help understand the <code>pannerNode</code> in better detail.</p>\n<p>We can relate:</p>\n<ul>\n <li>The position of objects</li>\n <li>The direction and movement of objects</li>\n <li>The environment (cavernous, underwater, etc.)</li>\n</ul>\n<p>This is especially useful in a three-dimensional environment rendered using WebGL, where the Web Audio API makes it possible to tie audio to the objects and viewpoints.</p>"}},{"type":"prose","value":{"id":"see_also","title":"See also","isH3":false,"content":"<ul>\n <li><a href=\"/en-US/docs/Web/API/Web_Audio_API\">Web Audio API on MDN</a></li>\n <li><a href=\"/en-US/docs/Web/HTML/Element/audio\"><code><audio></code> on MDN</a></li>\n <li><a href=\"https://hacks.mozilla.org/2013/10/songs-of-diridum-pushing-the-web-audio-api-to-its-limits/\" class=\"external\" target=\"_blank\">Songs of Diridum: Pushing the Web Audio API to Its Limits</a></li>\n <li><a href=\"https://pupunzi.open-lab.com/2013/03/13/making-html5-audio-actually-work-on-mobile/\" class=\"external\" target=\"_blank\">Making HTML5 Audio Actually Work on Mobile</a></li>\n <li><a href=\"https://remysharp.com/2010/12/23/audio-sprites/\" class=\"external\" target=\"_blank\">Audio Sprites (and fixes for iOS)</a></li>\n</ul>"}}],"toc":[{"text":"Mobile audio caveats","id":"mobile_audio_caveats"},{"text":"Mobile workarounds","id":"mobile_workarounds"},{"text":"See also","id":"see_also"}],"summary":"Audio is an important part of any game; it adds feedback and atmosphere. Web-based audio is maturing fast, but there are still many browser differences to navigate. We often need to decide which audio parts are essential to our games' experience and which are nice to have but not essential, and devise a strategy accordingly. This article provides a detailed guide to implementing audio for web games, looking at what works currently across as wide a range of platforms as possible.","popularity":0,"modified":"2024-10-25T00:08:46.000Z","other_translations":[{"locale":"de","title":"Audio für Webspiele","native":"Deutsch"},{"locale":"fr","title":"L'audio dans les jeux Web","native":"Français"},{"locale":"ja","title":"ウェブゲーム用の音声","native":"日本語"}],"pageType":"guide","source":{"folder":"en-us/games/techniques/audio_for_web_games","github_url":"https://github.com/mdn/content/blob/main/files/en-us/games/techniques/audio_for_web_games/index.md","last_commit_url":"https://github.com/mdn/content/commit/baac7f2a43813a7930ff97b11d9c38b413f97c78","filename":"index.md"},"short_title":"Audio for Web games","parents":[{"uri":"/en-US/docs/Games","title":"Game development"},{"uri":"/en-US/docs/Games/Techniques","title":"Techniques for game development"},{"uri":"/en-US/docs/Games/Techniques/Audio_for_Web_Games","title":"Audio for Web games"}],"pageTitle":"Audio for Web games - Game development | MDN","noIndexing":false}}</script></body></html>