The AudioLoader.load()
method is a part of the Three.js library, which is commonly used to create and display 3D graphics in web browsers. As the name implies, this method loads an audio file and returns an instance of the AudioBuffer
class. It can be used to load audio files in various formats, such as MP3, OGG, and WAV.
The syntax for using AudioLoader.load()
method is as follows:
audioLoader.load(url: String, onLoad?: function, onProgress?: function, onError?: function): AudioBuffer
url: String
- The URL of the audio file to be loaded. This parameter is required.onLoad?: function
- The function to be called when the audio file is loaded. This parameter is optional.onProgress?: function
- The function to be called when the loading progress is updated. This parameter is optional.onError?: function
- The function to be called when an error occurs during loading. This parameter is optional.The AudioLoader.load()
method returns an instance of the AudioBuffer
class, which represents the audio data that has been loaded. The returned AudioBuffer
object contains the decoded PCM audio data of the audio file.
Here is an example of using AudioLoader.load()
method to load an audio file:
const audioLoader = new THREE.AudioLoader();
const audioUrl = 'path/to/audio/file.mp3';
audioLoader.load(
audioUrl,
(audioBuffer) => {
const audio = new THREE.PositionalAudio(camera.audioListener);
audio.setBuffer(audioBuffer);
audio.play();
},
(xhr) => {
// Handle loading progress
},
(error) => {
console.error(error);
}
);
In the above example, the AudioLoader.load()
method is used to load an MP3 audio file at the specified URL audioUrl
. Once the audio file is loaded, the onLoad
callback function is called, which creates a PositionalAudio
object and sets the audioBuffer
as its buffer. Finally, the play()
method is called to play the audio.
AudioLoader
instance needs to be initialized before calling the load()
method.onLoad
callback function is not specified, the load()
method returns a Promise object that resolves to the AudioBuffer
object.onProgress
callback function can be used to display the loading progress of the audio file.onError
callback function will be called with an Error
object.In this article, we have discussed the AudioLoader.load()
method, which is used to load audio files in Three.js. We have covered its syntax, return value, example usage, and some important notes. We hope this article has helped you to understand this method better and use it in your projects.