Unity - How can I play audio when targets get detected

January 3, 2014 - 2:38am #1

This article illustrates how to play audio clips in response to target detection events, using the Unity Vuforia Extension.

Assuming you have created a Vuforia-based Unity project with an Image Target (e.g. by importing the Image Targets sample or by creating your own setup with an ARCamera and a properly configured Image Target), you can follow these basic steps:

  • attach an Audio Source component to your Image Target (note: Audio Source is a standard Unity component, it is not Vuforia-specific, see: http://docs.unity3d.com/Documentation/ScriptReference/AudioSource.html)
  • copy an audio file (e.g. wav, mp3,...) to the Assets folder of your project, so that the audio file also appears in the Project view in the Unity Editor
  • drag the Audio file from the Assets into the Audio Clip field of the Audio Source component that you have attached to your Image Target
  • in the Audio Source inspector, disable the Play On Awake checkbox (unless you want to play the clip at startup)
  • in the 3D Sounds Settings of your Audio Source, adjust the Max Distance so to make sure that the sound will be able to reach the audio listener of your ARCamera even when the distance from the Image Target is large (otherwise you may not be able to hear the sound); for example, increase the default value from 500 to 5000 (or whatever is appropriate to your specific scene setup)
  • optionally, you may want to change the Volume Rolloff settings to use a Linear rolloff instead of a Logarithmic one (this is optional and up to your specific application needs)
  • create a custom C# script, for instance called ImageTargetPlayAudio, which implements the ITrackableEventHandler interface, and attach it to your Image Target; the script should contain some code similar to the following example:
public class ImageTargetPlayAudio : MonoBehaviour,
    private TrackableBehaviour mTrackableBehaviour;

    void Start()
		mTrackableBehaviour = GetComponent<TrackableBehaviour>();
        if (mTrackableBehaviour)
    public void OnTrackableStateChanged(
                                    TrackableBehaviour.Status previousStatus,
                                    TrackableBehaviour.Status newStatus)
        if (newStatus == TrackableBehaviour.Status.DETECTED ||
            newStatus == TrackableBehaviour.Status.TRACKED ||
            newStatus == TrackableBehaviour.Status.EXTENDED_TRACKED)
			// Play audio when target is found
			// Stop audio when target is lost


Topic locked