728x90

Web Audio API는 개발자가 웹 애플리케이션에서 오디오를 만들고 조작할 수 있도록 하는 JavaScript API입니다. 실시간으로 오디오 스트림을 생성, 처리 및 조작하기 위한 강력한 도구 세트를 제공합니다. 다음은 Web Audio API를 사용하는 방법에 대한 몇 가지 예입니다.

1. 간단한 사운드 생성 및 재생:

// create an AudioContext

const audioContext = new AudioContext();

// create an oscillator node

const oscillator = audioContext.createOscillator();

oscillator.frequency.value = 440; // set frequency to 440 Hz

// connect the oscillator to the destination (speakers)

oscillator.connect(audioContext.destination);

// start the oscillator

oscillator.start();

이 예제에서는 AudioContext와 오실레이터 노드를 생성합니다. 오실레이터의 주파수를 440Hz(A 음표)로 설정하고 대상(스피커)에 연결하고 시작합니다.

2. 오디오 파일에서 사운드 만들기:

// create an AudioContext

const audioContext = new AudioContext();

// create a buffer source node

const sourceNode = audioContext.createBufferSource();

// load an audio file

fetch('audiofile.mp3')

.then(response => response.arrayBuffer())

.then(buffer => audioContext.decodeAudioData(buffer))

.then(decodedData => {

sourceNode.buffer = decodedData;

sourceNode.connect(audioContext.destination);

sourceNode.start();

});

이 예제에서는 AudioContext와 버퍼 소스 노드를 만듭니다. Fetch API를 사용하여 오디오 파일을 로드하고 `decodeAudioData()` 메서드를 사용하여 디코딩하고 소스 노드의 버퍼를 디코딩된 데이터로 설정합니다. 그런 다음 소스 노드를 대상에 연결하고 시작합니다.

3. 오디오 효과 적용:

// create an AudioContext

const audioContext = new AudioContext();

// create a buffer source node

const sourceNode = audioContext.createBufferSource();

// load an audio file

fetch('audiofile.mp3')

.then(response => response.arrayBuffer())

.then(buffer => audioContext.decodeAudioData(buffer))

.then(decodedData => {

// create a gain node

const gainNode = audioContext.createGain();

gainNode.gain.value = 0.5;

// create a lowpass filter node

const filterNode = audioContext.createBiquadFilter();

filterNode.type = 'lowpass';

filterNode.frequency.value = 5000;

// connect the nodes

sourceNode.connect(filterNode);

filterNode.connect(gainNode);

gainNode.connect(audioContext.destination);

// set the buffer of the source node and start it

sourceNode.buffer = decodedData;

sourceNode.start();

});

이 예에서는 오디오 파일을 로드하고 게인 노드와 저역 통과 필터 노드를 만듭니다. 게인 값을 0.5로 설정하고 필터 주파수를 5000Hz로 설정했습니다. 그런 다음 소스 -> 필터 -> 이득 -> 대상의 순서로 노드를 연결합니다. 마지막으로 소스 노드의 버퍼를 설정하고 시작합니다.

이는 Web Audio API로 할 수 있는 작업의 몇 가지 예일 뿐입니다. API는 지연 노드, 리버브 노드 및 컨볼루션 노드와 같이 오디오를 만들고 조작하기 위한 더 많은 노드와 메서드를 제공합니다. Web Audio API를 사용하면 복잡한 오디오 처리 체인을 생성하고 강력한 웹 기반 음악 및 오디오 애플리케이션을 구축할 수 있습니다.

728x90

+ Recent posts