Activate the audio playback when a marker is detected using A-frame and Ar.js, playing the audio only once

I'm having trouble playing a sound only once when a marker is detected using A-frame and AR.JS libraries.

Here's the code I've tried, but the sound keeps playing indefinitely:

<a-scene embedded arjs='sourceType: webcam; debugUIEnabled: false;'>
    <a-assets>
        <audio id="sound" src="audio.mp3" preload="auto"></audio>
    </a-assets>
    <a-marker preset="hiro">
        <a-entity id="examplemodel" gltf-model="./models/Example.glb" soundhandler></a-entity>
    </a-marker>
    <a-entity sound="src: #sound" autoplay="false"></a-entity>
    <a-entity camera></a-entity>
</a-scene>

<script>
AFRAME.registerComponent('soundhandler', {
    tick: function () {
        var entity = document.querySelector('[sound]');
        if (document.querySelector('a-marker').object3D.visible == true) {
            entity.components.sound.playSound();
        } else {
            entity.components.sound.pauseSound();
        }
    }
});
</script>

When I changed 'tick' to 'init', I got this error message:

Uncaught TypeError: Cannot read property 'playSound' of undefined

Can anyone offer suggestions on how to fix this issue?

Answer №1

The reason it seems to be playing indefinitely is because the playSound() function is being called on each render loop when the object is visible.

If you implement a simple toggle check, you can achieve the desired behavior of playing the sound only once when the object becomes visible:

tick: function() {
  // marker is the object3D of marker
  if (marker.visible && !this.markervisible) {
    // Perform actions here once when object is visible
    this.markervisible = true;
  } else if (!marker.visible) {
    this.markervisible = false;
  }
}

Feel free to try it out here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize a for loop to load data using JSON

Here's a question for you. Take a look at my code snippet: var data=[]; for(i=0;i<parametrTable.length;++i){ x = parametrTable[i]; (function(i) { if(i==0){ $.getJSON("myurlwithparametr", function(json) { ...

Struggling to grasp the coordinate and axes system in three.js

I am working with the code below: // coordinate values var x1 = -815723.5125568421; var y1 = 20538442.534868136; var z1 = -17.439584224846456; var x2 = -815723.5125568421; var y2 = 20538443.164575472; var z2 = -16.620415776398275; // creating a rectangul ...

Is it possible to stream audio using a web socket?

I'm currently working on an app that streams audio from a microphone using web sockets. I'm struggling to play the web socket response in an audio control. Can someone please provide guidance on how to play audio buffer in an audio control? Your ...

Is there a way to efficiently modify the positions of numerous markers on Google Maps while utilizing PhoneGap?

Hey there, I'm new to this and I have a service for tracking multiple cars. I'm using a timer to receive their locations, but I'm having trouble figuring out how to update the old marker with the new value. I've tried deleting all the m ...

Show a personalized Angular script template as a detailed row in a table

Hi, I'm new to Angular programming and I have a question about incorporating angular script templates into a table. I have a base directive table that shows data, but I want users of the directive to be able to customize how the details row looks. I ...

Reducing the size of a static top bar while scrolling, along with a secondary header

While searching for methods to resize the header of my website upon scrolling, I came across an example that worked well. You can view the working example on JsFiddle index <!DOCTYPE html> <html lang="en"> <head> ... </body> </ ...

Results from AWS DynamoDB Scan operation

I am currently utilizing the AWS JavaScript SDK for DynamoDB, and executing a scan operation to retrieve a list of items from a table. The returned results show that each value is enclosed within an attribute type key: For instance: An anticipated result ...

Error Encountered: AngularJS - 'DashboardController' is Not Registered

I just set up a new angular app and I'm encountering an issue where my controller is not registering. The error message I am receiving states: The controller with the name 'DashboardController' is not registered. My app module and dashbo ...

How can one retrieve elements from a dictionary array and create a new array?

I'm struggling with how to access elements from a dictionary within an array and create another dictionary in ReactJs. The data structure is as follows: [{name: "dad", data: 10}, {name: "mom", data: 20}, {name: "dad", data: 40}, {name: "mom", da ...

How to load an image from a different domain into a Three.js texture

When attempting to load an image using THREE.ImageUtils.loadTexture(url), I encountered an error due to the image being hosted on a different domain than the web page. The error received was: Uncaught SecurityError: Failed to execute 'texImage2D&apos ...

Is there a way to determine the image type from a link like this?

I am wondering how to determine the image type from a link like the one below: For example, in HTML like this: <img src="https://www.gravatar.com/avatar/71b0d516013802a2d67aeb7c2e77ed32?s=48&amp;d=identicon&amp;r=PG&amp;f=1" alt="" width= ...

Transformation of intricate object

I am currently in search of a reliable utility (such as Lodash) that can assist me in transforming deeply nested objects like the example shown below: Source Data: [{ "category": "blogs", "results": { "__type": "SearchProvider.SearchResultCon ...

Alter elements in HTML dynamically based on the value of a cookie

I am trying to dynamically change HTML links on my website based on a cookie variable that is set by PHP. The cookie value is updated every minute through a periodic request. To ensure that the JavaScript variable remains up-to-date, I want to check it e ...

AngularJS has encountered an error due to exceeding the maximum call stack size limit

Utilizing AngularJS and a web API, I am fetching data from an SQL table. I have designed a function that populates input fields with values when a row is selected from an HTML table. However, I encountered an error during debugging when clicking on any row ...

In JavaScript, promises remain in a pending state

How can I prevent my promises from remaining in the pending state and resolve them instead? var foundPeopleA = findPeopleA().then(function(result) { var res = [] result.map(function(el) { res.push(getProfileXML(el.sid)); ...

Is there a way to enable scanned data to be automatically inputted into a field without manual entry?

I am in the process of creating a user-friendly Android app for virtual inventory management. I want the application to streamline data input by automatically populating text fields upon scanning, eliminating the need for users to manually click on each fi ...

When utilizing image.width in JavaScript, it returns 0 exclusively when accessed online, but functions correctly when

Recently, I encountered a problem while rendering an image in React. I was using JavaScript to set the image width and applying it to the img style. let img = new Image(); img.src = "image_url"; let i_width = (img.width * 2.54) / 30; <img sr ...

Using REST API and AngularJS to sign in to asp.net

After successfully implementing a login page in ASP.NET with AngularJS and REST API integration, I am now looking to add an auto-generated token for added security measures. How can I achieve this login operation in ASP.NET using AngularJS and REST API? ...

The particular division is failing to display in its designated location

This is quite an interesting predicament I am facing! Currently, I am in the process of coding a website and incorporating the three.js flocking birds animation on a specific div labeled 'canvas-div'. My intention is to have this animation displa ...