webrtcStore.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. import { defineStore } from "pinia";
  2. import {
  3. MSG_TYPE,
  4. MESSAGE_TYPE_USER,
  5. MESSAGE_TYPE_GROUP,
  6. } from "@/common/constant/msgType";
  7. import { useWebSocketStore } from "@/stores/modules/webSocketStore";
  8. import * as Constant from "@/common/constant/Constant";
  9. export const useWebRTCStore = defineStore("webrtc", {
  10. state: () => ({
  11. // WebRTC 连接实例
  12. peerConnection: null,
  13. // ICE 候选信息
  14. iceCandidates: [],
  15. pendingIceCandidates: [], // 缓存未处理的候选
  16. // 连接状态
  17. connectionState: "disconnected",
  18. // 媒体流
  19. localStream: null, // 本地媒体流
  20. remoteStream: null, // 远端媒体流
  21. streamType: "audio", //"audio",
  22. // 视频元素引用
  23. localVideoElement: null,
  24. remoteVideoElement: null,
  25. // 媒体控制状态
  26. isVideoEnabled: true,
  27. isAudioEnabled: true,
  28. // 通话类型
  29. callType: "audio", // 'audio' 或 'video'
  30. // 是否是发起方
  31. isCaller: false,
  32. // 配置项
  33. config: {
  34. iceServers: [
  35. { urls: "stun:stun.l.google.com:19302" },
  36. // 可以添加更多 STUN/TURN 服务器
  37. ],
  38. },
  39. imSate: {
  40. videoCallModal: false, // 视频通话模态框
  41. callName: "", // 通话对象名称
  42. fromUserUuid: "", // 通话对象 uuid
  43. },
  44. }),
  45. actions: {
  46. //
  47. bindRemoteAudio() {
  48. // video && audio
  49. // 如果已经存在 audio 元素,先移除旧的
  50. const oldAudio = document.getElementById(`remote-audio`);
  51. if (oldAudio) {
  52. oldAudio.remove();
  53. }
  54. // 创建新的 <audio> 元素
  55. const audioElement = document.createElement("audio");
  56. audioElement.id = `remote-audio`;
  57. audioElement.autoplay = true; // 自动播放
  58. audioElement.muted = false; // 取消静音
  59. audioElement.controls = true; // 显示控制条(可选)
  60. audioElement.srcObject = this.remoteStream;
  61. // 添加到 DOM(可以放在任意位置,比如 body)
  62. document.body.appendChild(audioElement);
  63. console.log("✅ 远程音频已绑定到 <audio> 元素");
  64. },
  65. // 初始化 WebRTC 连接
  66. initConnection(isCaller) {
  67. this.cleanup();
  68. this.isCaller = isCaller;
  69. const wsStore = useWebSocketStore();
  70. try {
  71. this.peerConnection = new RTCPeerConnection();
  72. // 设置事件监听: 对等方收到ice信息后,通过调用 addIceCandidate 将接收的候选者信息传递给浏览器的ICE代理
  73. this.peerConnection.onicecandidate = (event) => {
  74. if (event.candidate) {
  75. let candidate = {
  76. type: this.isCaller ? "offer_ice" : "answer_ice",
  77. iceCandidate: event.candidate,
  78. };
  79. wsStore.sendMessage({
  80. content: JSON.stringify(candidate),
  81. type: Constant.MESSAGE_TRANS_TYPE,
  82. });
  83. this.iceCandidates.push(event.candidate);
  84. }
  85. };
  86. // 监听 ICE 状态变化
  87. this.peerConnection.onconnectionstatechange = () => {
  88. this.connectionState = this.peerConnection.connectionState;
  89. };
  90. // 当连接成功后,从里面获取语音视频流: 监听 ICE candidate:包含语音视频流
  91. this.peerConnection.ontrack = (event) => {
  92. // 添加远程媒体流
  93. if (!this.remoteStream) {
  94. this.remoteStream = new MediaStream();
  95. }
  96. // 添加远程媒体流
  97. event.streams[0].getTracks().forEach((track) => {
  98. this.remoteStream.addTrack(track);
  99. });
  100. };
  101. // 监听 ICE 连接状态(关键修复!)
  102. this.peerConnection.oniceconnectionstatechange = () => {
  103. const state = this.peerConnection.iceConnectionState;
  104. if (state === "connected") {
  105. console.log("✅ P2P 连接成功,可以开始语音通话!");
  106. if(this.streamType == "audio") this.bindRemoteAudio();
  107. } else if (state === "failed") {
  108. console.error("❌ ICE 连接失败,尝试重启...");
  109. this.restartICE();
  110. }
  111. };
  112. console.log("WebRTC 连接初始化成功");
  113. } catch (error) {
  114. console.error("初始化 WebRTC 连接失败:", error);
  115. this.cleanup();
  116. throw error;
  117. }
  118. },
  119. // 添加本地媒体流
  120. async addLocalStream(stream) {
  121. if (!this.peerConnection) {
  122. throw new Error("WebRTC 连接未初始化");
  123. }
  124. this.localStream = stream;
  125. stream.getTracks().forEach((track) => {
  126. this.peerConnection.addTrack(track, stream);
  127. });
  128. },
  129. // 创建 Offer
  130. async createOffer() {
  131. if (!this.peerConnection) {
  132. throw new Error("WebRTC 连接未初始化");
  133. }
  134. try {
  135. const offer = await this.peerConnection.createOffer();
  136. await this.peerConnection.setLocalDescription(offer);
  137. return offer;
  138. } catch (error) {
  139. console.error("创建 Offer 失败:", error);
  140. throw error;
  141. }
  142. },
  143. // 创建 Answer
  144. async createAnswer() {
  145. if (!this.peerConnection) {
  146. throw new Error("WebRTC 连接未初始化");
  147. }
  148. try {
  149. const answer = await this.peerConnection.createAnswer();
  150. await this.peerConnection.setLocalDescription(answer);
  151. return answer;
  152. } catch (error) {
  153. console.error("创建 Answer 失败:", error);
  154. throw error;
  155. }
  156. },
  157. // 设置远程描述后处理缓存
  158. async setRemoteDescription(desc) {
  159. await this.peerConnection.setRemoteDescription(desc);
  160. // 处理缓存的候选
  161. while (this.pendingIceCandidates.length > 0) {
  162. const candidate = this.pendingIceCandidates.shift();
  163. await this.peerConnection
  164. .addIceCandidate(candidate)
  165. .catch((e) => console.error(e));
  166. }
  167. },
  168. // 添加 ICE 候选
  169. async addIceCandidate(candidate) {
  170. if (!candidate) {
  171. console.warn("收到空的 ICE 候选");
  172. return;
  173. }
  174. // 如果是候选结束信号(candidate:null)
  175. if (candidate.candidate === "") {
  176. console.log("ICE 候选收集完成");
  177. return;
  178. }
  179. try {
  180. // 确保 PeerConnection 和远程描述已就绪
  181. if (!this.peerConnection) {
  182. this.pendingIceCandidates.push(candidate);
  183. return;
  184. }
  185. // Answer 方必须等待远程描述
  186. if (!this.peerConnection.remoteDescription && !this.isCaller) {
  187. this.pendingIceCandidates.push(candidate);
  188. return;
  189. }
  190. await this.peerConnection.addIceCandidate(candidate);
  191. console.log("✅ 成功添加 ICE 候选:", candidate.candidate);
  192. } catch (error) {
  193. console.error("❌ 添加 ICE 候选失败:", error);
  194. // 失败后重试缓存
  195. this.pendingIceCandidates.push(candidate);
  196. }
  197. },
  198. // 清理资源:挂断
  199. cleanup() {
  200. if (this.peerConnection) {
  201. this.peerConnection.close();
  202. this.peerConnection = null;
  203. }
  204. if (this.localStream) {
  205. this.localStream.getTracks().forEach((track) => track.stop());
  206. this.localStream = null;
  207. }
  208. this.iceCandidates = [];
  209. this.connectionState = "disconnected";
  210. },
  211. },
  212. });