이전 포스팅에서 컴퓨터에 연결되어 있는 마이크(audio input)를 찾는 방법에 대해 살펴보았다. 컴퓨터에 연결되어 있는 마이크, 카메라, 스피커 등 미디어 장치에 관련한 정보를 navigator.mediaDevices 객체가 관리한다. 이번 포스팅에서는 이 navigator.mediaDevices 객체를 통해 마이크에서 데이터를 가져오는 방법을 살펴보도록 하겠다.
navigator.mediaDevices의 enumerateDevice() 메서드를 이용하면 컴퓨터에 연결되어 있는 미디어 장치들을 열거할 수 있음을 이전 포스팅에서 살펴보았다.
2021.08.06 - [웹 오디오 프로그래밍] - [Web Audio API] 녹음하기 - 마이크 찾기
하지만 매번 사용자에게 신호 입력장치를 선택해달라고 요청하는 것은 사용자를 번거롭게 만든다. 따라서 보통은 사용자에게 매번 묻지 않고 기본 입력장치로 지정되어 있는 장치를 선택한다. navigator.mediaDevices 객체의 getUserMedia() 메서드에 아래와 같이 제약조건(constraints)를 전달하면 기본으로 지정되어 있는 오디오 입력 장치를 사용할 수 있다.
if(navigator.mediaDevices){
var constraints = {'video': false, 'audio': true};
navigator.mediaDevices.getUserMedia(constraints).then((stream) => {
// 오디오 스트림 사용
}).catch((error) => {
// 오디오 스트림을 얻지 못했을 경우 오류 처리
});
}
getUserMedia() 메서드 호출 결과 반환되는 프로미스를 통해 기본 마이크를 얻으면 오디오 컨텍스트의 createMediaStreamSource() 메서드를 호출해서 오디오 소스로 만들 수 있다. 이제 이 오디오 소스와 오디오 컴포넌트들로 오디오 그래프를 구성할 수 있다. 아래 예는 마이크 입력을 스피커로 연결시켜 마이크 입력을 바로 들을 수 있도록 하는 오디오 그래프의 예다.
const audioContext = new(window.AudioContext || window.webkitAudioContext)();
if(navigator.mediaDevices){
var constraints = {'video': false, 'audio': true};
navigator.mediaDevices.getUserMedia(constraints).then((stream) => {
// 오디오 소스 생성
streamSource = audioContext.createMediaStreamSource(stream);
// 오디오 그래프 구성
streamSource.connect(audioContext.destination);
}).catch((error) => {
console.log('[Error] getUserMedia: ', error);
});
}
마이크 입력신호를 연결하고 차단할 수 있도록 '듣기', '멈추기' 버튼 인터페이스와 함께 오디오 그래프를 구성하면 아래와 같이 응용할 수 있다.
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!-- 마이크 소리 듣기/멈추기 버튼 -->
<div id="audio_control_div">
<button id="listen_audio_input_button" data-listening="false">Listen</button>
</div>
</body>
<script>
const audioContext = new(window.AudioContext || window.webkitAudioContext)();
const ListenStopButton = document.querySelector('#listen_audio_input_button');
window.onload = () => {
if(navigator.mediaDevices){
var constraints = {'video': false, 'audio': true};
navigator.mediaDevices.getUserMedia(constraints).then((stream) => {
// 버튼을 클릭하면 마이크 소리 듣기/멈추기 토글
ListenStopButton.onclick = (event) => {
var listening = event.target.dataset.listening;
if(listening == 'false'){
event.target.dataset.listening = 'true';
event.target.innerHTML = 'Stop';
streamSource = audioContext.createMediaStreamSource(stream);
streamSource.connect(audioContext.destination);
if(audioContext.state === 'suspended'){
audioContext.resume();
}
}
else{
event.target.dataset.listening = 'false';
event.target.innerHTML = 'Listen';
streamSource.disconnect();
if(audioContext.state === 'running'){
audioContext.suspend();
}
}
}
}).catch((error) => {
console.log('[Error] getUserMedia: ', error);
});
}
}
</script>
위의 예에서는 [마이크 입력] → [스피커] 두 개의 컴포넌트로 이루어진 오디오 그래프를 구성했지만 gain control, filter, dynamic compressor등 Web Audio API가 지원하는 다양한 컴포넌트들과 함께 오디오 그래프를 구성할 수 있다.
■
'웹 오디오 프로그래밍' 카테고리의 다른 글
[Web Audio API #17] MediaRecorder를 이용한 녹음예제 (0) | 2021.08.13 |
---|---|
[Web Audio API #16] 녹음 - MediaRecorder (0) | 2021.08.10 |
[Web Audio API #14] 녹음하기 - 마이크 찾기 (0) | 2021.08.06 |
[Web Audio API #13] Audio buffer - Sample, Frame, 그리고 Sample rate (0) | 2021.08.03 |
[Web Audio API #12] 오디오 필터 사용하기 (0) | 2021.08.02 |
댓글