@4players/odin
Version:
A cross-platform SDK enabling developers to integrate real-time VoIP chat technology into their projects
77 lines (76 loc) • 2.22 kB
JavaScript
import { __awaiter } from "tslib";
export class OdinRtcHandler {
/**
* Creates a new `RtcHandler` instance.
*
* @param _worker The web worker to handle audio
*/
constructor(_worker, _rtc) {
this._worker = _worker;
this._rtc = _rtc;
this._audioChannel = this._rtc.createDataChannel('audio', {
id: 2,
negotiated: true,
ordered: false,
maxRetransmits: 0,
});
this._audioChannel.binaryType = 'arraybuffer';
this._audioChannel.onerror = (error) => console.error(error);
this._audioChannel.onmessage = (event) => {
if (this._worker) {
const bytes = new Uint8Array(event.data);
this._worker.postMessage({
type: 'packet',
bytes,
}, [bytes.buffer]);
}
};
}
/**
* Get the DataChannel for audio.
*/
get audioChannel() {
return this._audioChannel;
}
/**
* Returns a promise which resolves with data providing statistics about the RTC connection.
*
* @returns A promise providing connection statistics
*/
getStats() {
return __awaiter(this, void 0, void 0, function* () {
return this._rtc.getStats();
});
}
/**
* Starts WebRTC on the given stream.
*
* @param mainStream
*/
startRtc(mainStream) {
return __awaiter(this, void 0, void 0, function* () {
try {
const offer = yield this._rtc.createOffer();
yield this._rtc.setLocalDescription(offer);
const answer = (yield mainStream.request('SetupWebRtc', {
sdp: offer.sdp,
}));
yield this._rtc.setRemoteDescription({
type: 'answer',
sdp: answer.sdp,
});
}
catch (e) {
throw new Error('RPC SetupWebRtc failed\n' + e);
}
});
}
/**
* Close the RTC peer connection.
*/
stopRtc() {
if (this._rtc) {
this._rtc.close();
}
}
}