|
|
- // create Agora client
- var client = AgoraRTC.createClient({ mode: "rtc", codec: "vp8" });
-
- // Rtm
- var rtm_client = AgoraRTM.createInstance(window._APPID);
- rtm_client.login({ uid: window._MY_NAME, token: window._RTM_TOKEN});
-
- var rtm_channel = null;
-
- var localTracks = {
- audioTrack: null
- };
- var remoteUsers = {};
- // Agora client options
- var options = {
- appid: window._APPID,
- channel: null,
- uid: window._UID,
- token: null
- };
-
-
- function add_chat_text(s) {
- $('#chat-box').append($('<p></p>').text(s));
- $('#chat-box').animate({
- scrollTop: $("#chat-box")[0].scrollHeight
- }, 300);
- }
-
- $('.leave-btn').hide();
-
- $('#local-volume-range').on('input change', function() {
- if (localTracks.audioTrack)
- localTracks.audioTrack.setVolume(Math.floor($(this).val()**2));
- });
-
- $('.send-message').submit(async function (e) {
- e.preventDefault();
- if (!rtm_channel) {
- alert("还没有加入房间");
- return;
- }
- var inp = $(this).find('input');
- rtm_channel.sendMessage({'text': inp.val()}).then(() => {
- add_chat_text(window._MY_NAME + ': ' + inp.val());
- inp.val('');
- }).catch(error => {
- alert('发送失败', error);
- });
- });
-
- $('.join-form').submit(async function (e) {
- e.preventDefault();
- $(".join-btn").hide();
- $(this).serializeArray().forEach((v) => {
- options[v.name] = v.value;
- });
- options.uid = parseInt(options.uid);
- console.log(options);
- try {
- await join();
- $('.u-cnt').hide();
-
- rtm_channel = rtm_client.createChannel(options.channel);
- rtm_channel.join();
- rtm_channel.on('ChannelMessage', (message, user) => {
- console.log(message, user);
- if (message.messageType === 'TEXT') {
- add_chat_text(user + ': ' + message.text);
- }
- });
- rtm_channel.on('MemberJoined', memberId => {
- add_chat_text(`[${memberId} 加入了]`)
- });
- rtm_channel.on('MemberLeft', memberId => {
- add_chat_text(`[${memberId} 离开了]`)
- });
- } catch (error) {
- console.error(error);
- alert('出错啦\n' + error);
- window.location.reload();
- } finally {
- $(this).find(".leave-btn").show();
- }
- })
-
- $(".leave-btn").click(function (e) {
- leave();
- rtm_channel.leave();
- rtm_channel = null;
- $('#chat-box').empty();
- })
-
- function set_soundmeter(ele, at) {
- $(ele).val(($(ele).val() + at.getVolumeLevel())/2);
- }
-
- async function join() {
-
- // add event listener to play remote tracks when remote user publishs.
- client.on("user-published", handleUserPublished);
- client.on("user-unpublished", handleUserUnpublished);
-
- // join a channel and create local tracks, we can use Promise.all to run them concurrently
- [ options.uid, localTracks.audioTrack] = await Promise.all([
- // join the channel
- client.join(options.appid, options.channel, options.token || null, options.uid),
- // create local tracks, using microphone and camera
- AgoraRTC.createMicrophoneAudioTrack(),
- ]);
-
- localTracks.audioTrack.intervalId = window.setInterval(set_soundmeter, 25, '#local-player progress', localTracks.audioTrack);
-
- // publish local tracks to channel
- await client.publish(Object.values(localTracks));
- console.log("publish success");
- }
-
- async function leave() {
- var track = localTracks.audioTrack;
- if(track) {
- track.stop();
- track.close();
- window.clearInterval(track.intervalId);
- track = undefined;
- }
-
- // remove remote users and player views
- remoteUsers = {};
- $("#remote-playerlist").html("");
-
- // leave the channel
- await client.leave();
-
- $(".join-btn").show();
- $('.leave-btn').hide();
- console.log("client leaves channel success");
- }
-
- async function subscribe(user, mediaType) {
- const uid = user.uid;
- // subscribe to a remote user
- await client.subscribe(user, mediaType);
- console.log("subscribe success");
- $.getJSON(`api/user/${uid}`, function (user) {
- console.log(user);
- const player = $(`
- <div class="qbox" id="player-${uid}">
- <p>
- <a href="${user.url}" target="_blank">
- <img class="rounded-circle" src="${user.avat}" width="20">
- ${user.disp} @${user.acct}
- </a>
- )
- </p>
- <progress value="0" max="1"></progress>
- </div>
- `);
- $("#remote-playerlist").append(player);
- });
- user.audioTrack.play();
- user.intervalId = window.setInterval(set_soundmeter, 25, `#player-${uid} progress`, user.audioTrack);
- }
-
- function handleUserPublished(user, mediaType) {
- const id = user.uid;
- remoteUsers[id] = user;
- subscribe(user, mediaType);
- }
-
- function handleUserUnpublished(user) {
- window.clearInterval(user.intervalId);
- const id = user.uid;
- delete remoteUsers[id];
- $(`#player-${id}`).remove();
- }
|