|
| 1 | +const audioContainer = document.getElementById('voice-chat-audio-container'); |
| 2 | + |
| 3 | +const addAudioStream = ({ mediaConnection, peerMap }) => { |
| 4 | + const socketID = mediaConnection.peer; |
| 5 | + |
| 6 | + if (peerMap.has(socketID)) return; |
| 7 | + |
| 8 | + const audioElement = document.createElement('audio'); |
| 9 | + |
| 10 | + mediaConnection.on('stream', (stream) => { |
| 11 | + // eslint-disable-next-line no-param-reassign |
| 12 | + audioElement.srcObject = stream; |
| 13 | + audioElement.addEventListener('loadedmetadata', () => { |
| 14 | + audioElement.play(); |
| 15 | + }); |
| 16 | + audioContainer.append(audioElement); |
| 17 | + }); |
| 18 | + |
| 19 | + mediaConnection.on('close', () => { |
| 20 | + audioElement.remove(); |
| 21 | + }); |
| 22 | + |
| 23 | + peerMap.set(socketID, { |
| 24 | + mediaConnection, |
| 25 | + audioElement, |
| 26 | + }); |
| 27 | +}; |
| 28 | + |
| 29 | +// socket을 통해 다른 사람이 접속한걸 받았을 때 |
| 30 | +// 다른 사람에게 mediaConnection 요청을 보냄 |
| 31 | +const connectToNewUser = ({ peer, socketID, stream, peerMap }) => { |
| 32 | + const mediaConnection = peer.call(socketID, stream); |
| 33 | + addAudioStream({ mediaConnection, peerMap }); |
| 34 | +}; |
| 35 | + |
| 36 | +// 내가 다른 사람의 mediaConnection 요청을 받았을 때 |
| 37 | +const setAnswerBehavior = ({ stream, peerMap, peer }) => { |
| 38 | + peer.on('call', (mediaConnection) => { |
| 39 | + // 다른 사람의 요청에 answer를 날림 |
| 40 | + mediaConnection.answer(stream); |
| 41 | + addAudioStream({ mediaConnection, peerMap }); |
| 42 | + }); |
| 43 | +}; |
| 44 | + |
| 45 | +const getAudioStream = () => |
| 46 | + navigator.mediaDevices.getUserMedia({ |
| 47 | + audio: true, |
| 48 | + }); |
| 49 | + |
| 50 | +export { getAudioStream, setAnswerBehavior, connectToNewUser }; |
0 commit comments