Skip to content

WebRTC Audio 연결하기

Heewon123 edited this page Oct 19, 2017 · 8 revisions

WebRTC Audio 연결하기

용어 정리

  • 기가지니 클라이언트 : API를 이용하여 기가지니 단말에서 사용하는 클라이언트
  • 웹 클라이언트 : 기가지니 단말과 연결되는 다른 웹 클라이언트 (사용법은 웹 소켓 이용방법 을 참고하세요)

준비 사항

  • 기가지니 클라이언트에서 appinfo.getContainerId 로 Container ID를 미리 받으세요.
    Container ID는 웹 클라이언트에서 웹 소켓 인증 시 UUID로 사용됩니다.
    자세한 내용은 웹 소켓 이용방법인증된 ContainerId 받기 를 참고하세요.

전체 이용 플로우

  • (기가지니) CreateChannel -> (웹) Join session -> (기가지니) StartWebRTCAudio -> (기가지니 또는 웹) StopWebRTCAudio -> (기가지니 또는 웹) destroyChannel 순으로 진행됩니다.

  • image

세부 이용 플로우

  1. 기가지니 클라이언트에서 Channel을 생성합니다.
    CreateChannel 를 이용하여 데이터를 전송하기 위한 Channel을 생성합니다.

※ WebRTC 연결을 60초 이상 유지하고 싶을 때는 keepaliveChannel 을 이용합니다.

  • 기가지니 클라이언트 예시
var sessionId;
var ct;
var useid;
var ticker = 0;
var intervalId;
function createChannel(){
        var options={};
        options.channeltype="webrtcaudio";
        options.usecontainerid=false;
        gigagenie.media.createChannel(options,function(result_cd,result_msg,extra){
                if(result_cd===200){
                        sessionId=extra.sessionid;
                        console.log("Session ID:"+extra.sessionid);
                } else {
                        console.log("Error Result_cd:"+result_cd+" Msg:"+result_msg);
                }
        });
        // Keep Alive 설정
        intervalId = setInterval(function(){
                ticker++;
                if(ticker % 30 ===7){
                        console.log('keepalive:'+ticker);
                        gigagenie.media.keepaliveChannel(null,function(result_cd,result_msg,extra){
                                console.log("result_cd: "+result_cd+", result_msg: "+result_msg+", extra: "+JSON.stringify(extra));
                        });
                }
        },1000);
};
  1. 웹 클라이언트에서 1에서 생성한 Channel로 [Join Session]을 요청합니다.
  • 웹 클라이언트 예시
//최초 서버 접속 시 인증 필요
if(msg.msgtype === 'notify'){
	if (msg.operation === 'iam') {
		var auth_message = {
			"msgtype": "request",
			"operation": "auth",
			"uuid": uuid,
			"channeltype": "webrtcaudio",
		};
		ws.send(JSON.stringify(auth_message));
		console.log('auth message sent. auth_message= '+JSON.stringify(auth_message));
	}
}
else if (msg.msgtype === 'reply') {
	// 인증 후 join session 요청
	if (msg.operation == 'auth') {
		if (msg.result_cd == 200) {
			var join_session = {
				"msgtype": "request",
				"operation": "join_session",
				"channeltype": "webrtcaudio",
				"sessionid": sessionid,
				"uuid": uuid
		};
		ws.send(JSON.stringify(join_session));
		console.log('join_session message sent.');
		//채널 연결 유지
		var ticker = 0;
		intervalId = setInterval(function() {
			ticker++;
			if(ticker % 30 === 7){
				console.log('@ras-alive:' + ticker);
				var alive_session = {
					"msgtype":"notify",
					"operation":"ras_alive",
					"channeltype":"system"
				};
				ws.send(JSON.stringify(alive_session));
			},1000);
                 }
	}
}
  1. 기가지니 클라이언트에서 StartWebRTCAudio를 이용하여 WebRTC Offer를 전송하고 WebRTC 연결을 시도합니다.
    ※ 웹 클라이언트에서 Offer 전송은 불가합니다.
  • 기가지니 클라이언트 예시
function startWebRTCAudio(){
        var options={};
        options.sessionid=sessionId;
        gigagenie.media.startWebRTCAudio(options,function(result_cd,result_msg,extra){
                console.log("result_cd:"+result_cd+" result_msg:"+result_msg+" extra:"+JSON.stringify(extra));
        });
}
  1. 웹 클라이언트에서 WebRTC Offer를 받고 [Send data]로 Answer를 전송합니다.
  • 웹 클라이언트 예시
//WebRTC 실행
if (msg.msgtype === 'data') {
	console.log('type: '+msg.msgtype);
	if(msg.data.type === 'offer'){ //offer를 받았을 경우
		console.log('msg.data.sdp: '+JSON.stringify(msg.data.sdp));
		remoteDescription.sdp = msg.data.sdp;
		remoteDescription.type = "offer";

		//peerconnection 연결 및 answer 생성
        	createPeerConnection();
        	navigator.webkitGetUserMedia({"audio":true,"video":false}, function(stream){
                        console.log("addding local stream");
                        localAudio.src = URL.createObjectURL(stream);
                        localStream = stream;
                        pc.addStream(localStream);
			console.log('Sending answer to peer.');
			if(isInit) pc.createAnswer(setLocalAndSendMessage,onCreateSessionDescriptionError);
        	},logError);
		console.log('addstream success');
		pc.setRemoteDescription(new RTCSessionDescription(remoteDescription),function(){console.log('Set Remote Description Success. remoteDescription= '+pc.remoteDescription);},logError);
		var stream=pc.getRemoteStreams()[0];
	}         
	else if(msg.data.type === 'candidate'){
		console.log('addIceCandidate');
		var candidate = new RTCIceCandidate({
			sdpMLineIndex: msg.data.label,
			candidate: msg.data.candidate
		});
		pc.addIceCandidate(new RTCIceCandidate(candidate));
	}
	pc.oniceconnectionstatechange=function(evt){
		console.log('ice connection change: '+pc.iceConnectionState);
		if(pc.iceConnectionState === 'disconnected' || pc.iceConnectionState === 'failed'){
			audio.src = "";
			pc.close();
			ws.close();
			clearInterval(intervalId);
		} 
		console.log(evt);
	}
};
  1. 기가지니 클라이언트에서 WebRTC를 종료하고 싶을 때 stopWebRTCAudio를 이용합니다.
    외부 클라이언트는 새로고침하면 종료되며 종료 시 ICE 상태가 DISCONNECTED -> CLOSED 로 변경됩니다.
  • 기가지니 클라이언트 예시
function stopWebRTCAudio(){
        var options={};
        options.sessionid=sessionId;
        gigagenie.media.stopWebRTCAudio(options,function(result_cd,result_msg,extra){
                console.log("result_cd:"+result_cd+" result_msg:"+result_msg+" extra:"+JSON.stringify(extra));
                alert("result_cd:"+result_cd+" result_msg:"+result_msg+" extra:"+JSON.stringify(extra));
        });
}
  1. 사용한 Channel을 삭제하려면 기가지니 클라이언트에서 destroyChannel를 이용합니다.
    웹 클라이언트는 [destroy session]을 이용합니다.
  • 기가지니 클라이언트 예시
function destroyChannel(){
        var options={};
        options.channeltype=ct;
        options.sessionid=sessionId;
        gigagenie.media.destroyChannel(options,function(result_cd,result_msg,extra){
                if(result_cd===200){
                        console.log("destoryChannel Success.");
                } else {
                        console.log("Error Result_cd:"+result_cd+" Msg:"+result_msg);
                }
        });
        clearInterval(intervalId); //연결 유지를 했다면 해제하기
};
  • 외부 클라이언트 예시
var mSendDestroySessionTrx;
function sendDestroyMsg(){
        var sendMsg={};
        sendMsg.msgtype='request';
        sendMsg.operation='destroy_session';
        sendMsg.sessionid=sessionid;
        sendMsg.channeltype='webrtcaudio';
        mSendDestroySessionTrx='FromWeb:'+getTrxId();
        console.log('Send To WS:'+JSON.stringify(sendMsg));
        ws.send(JSON.stringify(sendMsg));
};

UserGuide

Clone this wiki locally