Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active May 14, 2023 01:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save primaryobjects/66516de4423f302856ecb82f23edb07e to your computer and use it in GitHub Desktop.
Save primaryobjects/66516de4423f302856ecb82f23edb07e to your computer and use it in GitHub Desktop.
How to use A-Frame audio sound in iOS iPhone Safari mobile web browser.

A-Frame Audio Sound in iOS

The iPhone has certain restrictions in playing audio in the web browser. This example shows how to successfully play audio on mobile.

The sound effect will play when the camera moves within a certain distance of the target object. The user will need to tap the iPhone screen (once) to allow sounds to play.

Quick Start

  1. Add script.js to your project.
  2. Add the script link to howler in your project.
  3. Add an <assets> section that lists your audio files.
  4. To add audio to element when the camera moves close to it, include an audio attribute as shown below.
    <a-box src="url(images/box.png); audio="src: #mysound; loop: true;"></a-box>
  5. Tap the iPhone screen after opening the app. This user action is required in order to allow sounds in the iOS web browser.

Notes

Sound module in A-Frame.

Free sound effects.

<html>
<head>
<script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/howler@2.2.1/dist/howler.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<a-scene>
<assets>
<audio id="mysound" src="mysound.mp3" preload="auto"></audio>
</assets>
<a-box src="url(images/box.png); audio="src: #mysound; loop: true;"></a-box>
<a-entity id="rig" movement-controls>
<a-entity camera look-controls="pointerLockEnabled: true"></a-entity>
</a-entity>
</a-scene>
</html>
AFRAME.registerComponent('audio', {
schema: {
src: { type: 'audio' },
loop: { type: 'boolean' },
volume: { type: 'int', default: 1 },
distance: { type: 'int', default: 8 },
fade: { type: 'int', default: 5000 },
},
init: function() {
this.sound = new Howl({
src: [ this.data.src ],
loop: this.data.loop,
volume: this.data.volume
});
this.camera = document.getElementById('rig');
},
tick: function() {
const objPos = this.el.object3D.position;
const camPos = this.camera.object3D.position;
const distance = objPos.distanceTo(camPos);
if (!this.audioId && distance < this.data.distance) {
this.audioId = this.sound.play();
this.sound.fade(0, 1, this.data.fade, this.audioId);
}
else if (this.audioId && distance >= this.data.distance) {
this.sound.fade(1, 0, this.data.fade, this.audioId);
this.audioId = null;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment