BufferGeometry
Object3D
Raycaster
Camera
CubeCamera
PerspectiveCamera
OrthographicCamera
StereoCamera
Clock
Curve
CurvePath
Path
Shape
ShapePath
ArrowHelper
AxesHelper
BoxHelper
Box3Helper
CameraHelper
DirectionalLightHelper
GridHelper
PolarGridHelper
HemisphereLightHelper
PlaneHelper
PointLightHelper
SkeletonHelper
SpotLightHelper
Light
PointLight
RectAreaLight
SpotLight
DirectionalLight
HemisphereLight
LightShadow
PointLightShadow
AnimationLoader
AudioLoader
BufferGeometryLoader
CompressedTextureLoader
CubeTextureLoader
DataTextureLoader
FileLoader
ImageBitmapLoader
ImageLoader
Loader
LoaderUtils
MaterialLoader
ObjectLoader
TextureLoader
LoadingManager
Material
Box2
Box3
Color
Cylindrical
Euler
Frustum
Interpolant
Line3
MathUtils
Matrix3
Matrix4
Plane
Quaternion
AnimationAction
AnimationClip
AnimationMixer
AnimationObjectGroup
AnimationUtils
keyframeTrack
PropertyBinding
PropertyMixer
BooleanKeyframeTrack
QuaternionKeyframeTrack
StringKeyframeTrack
Audio
AudioAnalyser
AudioContext
AudioListener
PositionalAudio

AudioContext.setContext()

AudioContext.setContext() 是 Three.js 中的一个 AudioContext 类的方法。它用于设置 Three.js 内部的音频环境。

语法

AudioContext.setContext( context );

参数

  • context: AudioContext 类型,需要设置的音频上下文对象。

示例

以下代码展示了如何使用 AudioContext.setContext 方法:

const renderer = new THREE.WebGLRenderer();
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 1000 );
const listener = new THREE.AudioListener();
const sound = new THREE.PositionalAudio( listener );
const context = new AudioContext();

let mesh;

// add a geometry
const geometry = new THREE.BoxGeometry();

// add a material
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );

// create a mesh
mesh = new THREE.Mesh( geometry, material );

// set position
mesh.position.set( 0, 0, -5 );

// add mesh to scene
scene.add( mesh );

// set context
THREE.AudioContext.setContext( context );

// create sound buffer
const buffer = context.createBuffer( 1, 4096, context.sampleRate );
const data = buffer.getChannelData( 0 );

for ( let i = 0; i < 4096; i++ ) {
    data[i] = Math.random() * 2 - 1;
}

// set sound buffer
sound.setBuffer( buffer );

// update listener position
function update() {
    requestAnimationFrame( update );

    const time = Date.now() * 0.001;
    const x = Math.sin( time ) * 5;
    const z = Math.cos( time ) * 5;

    camera.position.set( x, 1, z );

    sound.position.copy( mesh.position );

    renderer.render( scene, camera );
}

update();

注意事项

使用 AudioContext.setContext() 方法前,应该先创建一个 AudioContext 实例,同时也需要确保浏览器支持 Web Audio API。

当修改 Three.js 中的音频上下文对象时,已存在的音频对象会被自动销毁,重新创建一个新的音频对象。

参考文献