Sound Effect
INFO
It takes about 15 minutes to read this article
Adding music to your projects can increase game immersion and enhance performance. Search and use sound assets in the asset library for free. Control the playback status of sound through the Sound Effect object. You can also modify the properties of the Sound Effect object to control the sound playback effect.
Sound Object
[Sound] An object that plays sound in a project. The editor assigns a unique asset ID to each sound asset in the Asset Library, which you can assign to a Sound Effect object for playback. You can customize the properties of the Sound Effect object to make sound assets play as intended, for example, by setting it to auto-play when the game starts. You can also call the Sound object's API from a script to play it. In the Asset Library, you can search for and use various free sound assets. Dragging sound assets into the scene will bring you a corresponding Sound Effect object.
Create Sound Object
Create by placing assets:
[Sound] As a game object, it can exist in the game scene. Drag sound assets from the Asset Library into the Scene or Object Manager to automatically generate a Sound Effect object with the corresponding sound asset.
- Search for the sound asset you want in Asset Library
- Drag an object into the Scene or under the Object Manager
- Find the corresponding Sound Effect object in the Object Manager on the right and customize it.
Create from script:
You can also dynamically generate a corresponding Sound Effect object from the sound asset ID in the Asset Library while the game is running through scripts. This example uses the asset with ID 12721 for demonstration. You can also select your favorite sound asset in the Asset Library. Create a new script file in the script directory under "Project Content," and add the following sample code to the script's onStart
method: The sample code asynchronously generates a corresponding Sound Effect by passing the sound asset ID "12721" in the client's asyncSpawnGameObject
interface (the object location generated by the interface defaults to the world origin). To judge the success of object generation, you can print the gameObjectId of the generated object by console.log(
) and view the printed output in the Client window in the Output Window. Dynamically generated sound objects are not automatically enabled, so the code sets the isLoop
property to true and calls the play
interface to play the sound after looping. Drag the saved script into the Object Manager to run the game and hear the sound.
if(SystemUtil.isClient()) {
let audio = await GameObject.asyncSpawn("12721") as Sound;
console.log("audio's gameObjectId is" + audio.gameObjectId);
audio.isisLoop = true;
audio.play();
}
if(SystemUtil.isClient()) {
let audio = await GameObject.asyncSpawn("12721") as Sound;
console.log("audio's gameObjectId is" + audio.gameObjectId);
audio.isisLoop = true;
audio.play();
}
TIP
It should be noted that the Sound Effect exists only on the client side and is a single C-side game object. The Sound Effect object in the Object Manager will indicate its network status. Since there is no Sound Effect on the server, you need to obtain and generate Sound Effect on the client side in the script.
Custom Sound Object
Properties of [Sound] will determine the user's experience of enjoying the sound in the game, for example:
- The
volume
at which the user hears a specific sound. - The volume maintains an undiminished distance (
attenuationShapeExtents
). - The farthest range of the user's perceived sound attenuation (
falloffDistance
). is spatialization
of that sound.- Auto playback (
isisLoop
) when sound is complete.
......
In the Object Manager, find the corresponding Sound Effect in the Object column. When selected, we can view its property panel, through which we can modify some properties of the Sound Effect. If you do not want to operate the Sound Effect in the script, you can select Auto Enable and Loop Playback on the Properties panel and modify other properties, and the Sound Effect will loop automatically when the game runs.
Sound Duration
Sound duration
refers to the duration, in milliseconds (ms), of an sound asset loaded by Sound Effect, a read-only property. Time generally used to acquire sound assets for timing functions or other operations. Note that this property does not currently support controlling the sound playback rate. The following code example prints the sound duration in the Output Window:
console.log("sound time is" + audio.timeLength);
console.log("sound time is" + audio.timeLength);
Sound playback status
Sound playState
refers to whether Sound is currently playing, a Boolean value. True for playing, false for not playing, read-only property. It is generally used to determine the playback status of Sound Effect for the next operation. The following code example prints the sound playback status in the Output Window:
console.log("sound playing" + audio.playState);
console.log("sound playing" + audio.playState);
UI Sound
The UI sound uiSound
determines whether the sound object is the UI sound of the game. It is a Boolean value. True for UI sound, false for not UI sound, readable and writable. The difference between UI sound and spatial sound is that UI sound is 2D sound, independent of spatial (spatialization of sound, radius of sound) and gameplay restrictions such as pauses.
Attenuation of sound
AttenuationDistanceModel
mainly refers to the attenuation curve of the volume. The attenuationDistanceModel
property allows you to decide how sound decays as the distance between the user and the Sound object increases. Set this property to one of the four values in the AttenuationDistanceModel
enumeration.
Mode of decay | Description |
---|---|
Linear | The volume decays linearly between the inner and outer volume diameters. Once the user exceeds the volume outside diameter, the sound is muted. |
Logarithmic | Volume decays exponentially between the inner and outer volume diameters. Once the user exceeds the volume outside diameter, the sound is muted. |
Inverse | The volume decays inversely between the inner and outer volume diameters. Once the user exceeds the volume outside diameter, the sound is muted. |
LogReverse | The volume inversely decays exponentially between the inner and outer volume diameters. Once the user exceeds the volume outside diameter, the sound is muted. |
Auto Enable
The autoPlay
property determines whether sound is automatically enabled. is a Boolean value. True means that Sound Effect will play automatically, false means that it will not play automatically. This property is visible only in the Property Panel.
Current playback duration progress
The current playback duration progress timePosition
property displays the position in milliseconds (ms) of the sound asset currently heard by the user. This property can be used to play only a portion of the sound sample or trigger events for in-game logic when the sound reaches a specific location.
Loop playback
Loop the iSCSILoop
property to allow you to repeat the sound after it has finished playing. is a Boolean value. True means that the sound from Sound Effect will be played again, false means that it is not looping and can be read and written. This property is useful for applying to background sound BGMs to ensure that there is no sudden mute in the game. The following code example sets the Sound Effect to loop after looping playback by calling the playback interface:
audio.isisLoop = true;
audio.play();
audio.isisLoop = true;
audio.play();
Spatial Sound
The Spatialization isSpatialization
property of sound controls whether 3D sound is affected by a spatial range. isSpatialization
is a Boolean value. True means that the Sound Effect is a spatial sound effect, false means that it is a global sound effect, readable and writable. This property is not valid for UI sound, and turning on sound spatialization is a necessary condition for sound attenuation to take effect.
Sound attenuation range
TIP
The value of the decay distance falloffDistance
refers to the distance/angle from the internal to the external decay range.
Attenuation range and attenuationShapeExtents
and sound attenuation distance falloffDistance
determine the range of volume the user perceives from spatial sound effects. Both Properties require isSpatialization
of sound to be enabled for them to take effect. For spatial sound effects, the sound attenuation inner diameter attenuationShapeExtents
is the minimum distance the sound volume begins to decrease when the client's listeners are away from the Sound Effect. i. e. within that inn diameter of the sound attenuation effect. Within the falloffDistance
property, is the maximum decay distance from the sound that the client listener can hear. i. e. outside that sound attenuation path, the users cannot hear the sound. Between the sound decay inner diameter and the volume decay outer diameter, the sound volume is decayed according to the sound effect's volume decay attenuationDistanceModel
property.
Volume Ratio
The Volume Ratio volume
property allows you to set the sound volume to 0 (mute) to 1 (sound volume).
sound asset ID
[Sound] Just an object that plays sound, you can setSoundAsset
to set the sound it plays.
audio.setSoundAsset("13827");
audio.setSoundAsset("13827");
Use Sound Object
Flowchart of sound effects:
Get Sound Object
There are two ways to get Sound Effects in a script.
[Sound] Under Objects in Object Manager:
Use the asyncFind
interface to obtain:
Select Sound Effect and right-click Copy Object ID to obtain its gameObjectId. Note here the gameObjectId that distinguishes between the ID of the sound asset and the Sound Effect, which do not refer to the same object.
Add the following code to the script's
onStart
method: The code will asynchronously find the object corresponding to the ID and receive it in Sound.
if(SystemUtil.isClient()) {
let audio = await GameObject. asyncFindGameObjectById("Object ID obtained in the previous step") as Sound;
}
if(SystemUtil.isClient()) {
let audio = await GameObject. asyncFindGameObjectById("Object ID obtained in the previous step") as Sound;
}
Get it by script mount:
- Mount the script under Sound
- Add the following code to the script's
onStart
method: The code retrieves the script's mounted objects and receives them in Sound Effects.
if(SystemUtil.isClient()) {
let audio = this.gameObject as Sound;
}
if(SystemUtil.isClient()) {
let audio = this.gameObject as Sound;
}
Dynamically generated [Sound]
Add the following sample code to the script's onstart
method: The sample code generates a corresponding Sound Effect asynchronously from the client to the asyncSpawn
interface (passing in sound asset ID '12721').
if(SystemUtil.isClient()) {
let audio = await GameObject.asyncSpawn("12721") as Sound;
}
if(SystemUtil.isClient()) {
let audio = await GameObject.asyncSpawn("12721") as Sound;
}
Play sound objects
TIP
The sound effect cannot be played repeatedly. If the sound effect is in the playing state, the call to the play
interface is invalid. Pause or stop and replay is also through the play
interface.
After obtaining the Sound Effect, you can play the sound effect through the play
interface. In addition, a sound start event is provided in Sound Effect, which triggers each time Sound Effect starts playing. You can add other code logic to the sound start event, each time as the Sound Effect plays. Add the following sample code to the previous sample code for obtaining a sound effect object:In the example, we add print logic to the sound start event, and each playback prints a line of output on the client Output Window. We've also added a button method that calls the play
interface to play sound every time you press the keyboard "1."
audio.isLoop = false; // Remember to turn loop playback off here (also check the property panel) to avoid interference.
audio.onPlay.add(() => {
console.log("audio" + audio.gameObjectId + "Start playback");
});
InputUtil.onKeyDown(Type.Keys.One, () => {
audio.play();
});
audio.isLoop = false; // Remember to turn loop playback off here (also check the property panel) to avoid interference.
audio.onPlay.add(() => {
console.log("audio" + audio.gameObjectId + "Start playback");
});
InputUtil.onKeyDown(Type.Keys.One, () => {
audio.play();
});
Pause Sound Object
TIP
The sound effect cannot be paused repeatedly. If the sound effect is in a paused state, the call to the pause
interface is invalid. The pause
interface works only when playing.
After obtaining the Sound Effect, you can pause the sound effect through the pause
interface. In addition, a sound pause event is provided in the Sound Effect, which triggers each time the Sound Effect pauses. You can add other code logic to the sound pause event, each time with the pause of the Sound Effect. Add the following sample code to the sample code in the previous paragraph that plays the sound object:In the example, we add print logic to the sound pause event, and each pause prints a line of output on the client Output Window. We have also added a button method that calls the pause
interface to pause the sound every time you press the "2" button on the keyboard.
audio.onPause.add(() => {
console.log("audio" + audio.gameObjectId + "Pause");
});
InputUtil.onKeyDown(Type.Keys.Two, () => {
audio.pause();
});
audio.onPause.add(() => {
console.log("audio" + audio.gameObjectId + "Pause");
});
InputUtil.onKeyDown(Type.Keys.Two, () => {
audio.pause();
});
Stop Sound Object
TIP
The sound cannot be stopped repeatedly. If the sound is stopped, the call to the stop
interface is invalid. Calling the stop
interface on both playback and pause stops.
After obtaining the Sound Effect, you can stop the sound effect through the stop
interface. In addition, the Sound Effect provides a sound stop event that fires when the Sound Effect stops. You can add other code logic to the sound stop event, each time with the stop of the Sound Effect. Add the following sample code to the sample code for the pause sound object in the previous paragraph:In the example, we add print logic to the sound stop event, and each stop prints a line of output on the client Output Window. We have also added a button method, each time you press the keyboard "3" button, it will call the stop
interface to stop the sound effect.
audio.onFinish.add(() => {
console.log("audio" + audio.gameObjectId + "End");
});
InputUtil.onKeyDown(Type.Keys.Three, () => {
audio.stop();
});
audio.onFinish.add(() => {
console.log("audio" + audio.gameObjectId + "End");
});
InputUtil.onKeyDown(Type.Keys.Three, () => {
audio.stop();
});