webrtcStore.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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, video) {
  67. this.cleanup();
  68. this.isCaller = isCaller;
  69. this.streamType = video ? "video" : "audio";
  70. const wsStore = useWebSocketStore();
  71. try {
  72. this.peerConnection = new RTCPeerConnection();
  73. // 设置事件监听: 对等方收到ice信息后,通过调用 addIceCandidate 将接收的候选者信息传递给浏览器的ICE代理
  74. this.peerConnection.onicecandidate = (event) => {
  75. if (event.candidate) {
  76. let candidate = {
  77. type: this.isCaller ? "offer_ice" : "answer_ice",
  78. iceCandidate: event.candidate,
  79. };
  80. wsStore.sendMessage({
  81. content: JSON.stringify(candidate),
  82. type: Constant.MESSAGE_TRANS_TYPE,
  83. });
  84. this.iceCandidates.push(event.candidate);
  85. }
  86. };
  87. // 监听 ICE 状态变化
  88. this.peerConnection.onconnectionstatechange = () => {
  89. this.connectionState = this.peerConnection.connectionState;
  90. };
  91. // 当连接成功后,从里面获取语音视频流: 监听 ICE candidate:包含语音视频流
  92. this.peerConnection.ontrack = (event) => {
  93. // 添加远程媒体流
  94. if (!this.remoteStream) {
  95. this.remoteStream = new MediaStream();
  96. }
  97. // 添加远程媒体流
  98. event.streams[0].getTracks().forEach((track) => {
  99. this.remoteStream.addTrack(track);
  100. });
  101. };
  102. // 监听 ICE 连接状态(关键修复!)
  103. this.peerConnection.oniceconnectionstatechange = () => {
  104. const state = this.peerConnection.iceConnectionState;
  105. if (state === "connected") {
  106. console.log("✅ P2P 连接成功,可以开始语音通话!");
  107. if(this.streamType == "audio") this.bindRemoteAudio();
  108. } else if (state === "failed") {
  109. console.error("❌ ICE 连接失败,尝试重启...");
  110. this.restartICE();
  111. }
  112. };
  113. console.log("WebRTC 连接初始化成功");
  114. } catch (error) {
  115. console.error("初始化 WebRTC 连接失败:", error);
  116. this.cleanup();
  117. throw error;
  118. }
  119. },
  120. // 添加本地媒体流
  121. async addLocalStream(stream) {
  122. if (!this.peerConnection) {
  123. throw new Error("WebRTC 连接未初始化");
  124. }
  125. this.localStream = stream;
  126. stream.getTracks().forEach((track) => {
  127. this.peerConnection.addTrack(track, stream);
  128. });
  129. },
  130. // 创建 Offer
  131. async createOffer() {
  132. if (!this.peerConnection) {
  133. throw new Error("WebRTC 连接未初始化");
  134. }
  135. try {
  136. const offer = await this.peerConnection.createOffer();
  137. await this.peerConnection.setLocalDescription(offer);
  138. return offer;
  139. } catch (error) {
  140. console.error("创建 Offer 失败:", error);
  141. throw error;
  142. }
  143. },
  144. // 创建 Answer
  145. async createAnswer() {
  146. if (!this.peerConnection) {
  147. throw new Error("WebRTC 连接未初始化");
  148. }
  149. try {
  150. const answer = await this.peerConnection.createAnswer();
  151. await this.peerConnection.setLocalDescription(answer);
  152. return answer;
  153. } catch (error) {
  154. console.error("创建 Answer 失败:", error);
  155. throw error;
  156. }
  157. },
  158. // 设置远程描述后处理缓存
  159. async setRemoteDescription(desc) {
  160. await this.peerConnection.setRemoteDescription(desc);
  161. // 处理缓存的候选
  162. while (this.pendingIceCandidates.length > 0) {
  163. const candidate = this.pendingIceCandidates.shift();
  164. await this.peerConnection
  165. .addIceCandidate(candidate)
  166. .catch((e) => console.error(e));
  167. }
  168. },
  169. // 添加 ICE 候选
  170. async addIceCandidate(candidate) {
  171. if (!candidate) {
  172. console.warn("收到空的 ICE 候选");
  173. return;
  174. }
  175. // 如果是候选结束信号(candidate:null)
  176. if (candidate.candidate === "") {
  177. console.log("ICE 候选收集完成");
  178. return;
  179. }
  180. try {
  181. // 确保 PeerConnection 和远程描述已就绪
  182. if (!this.peerConnection) {
  183. this.pendingIceCandidates.push(candidate);
  184. return;
  185. }
  186. // Answer 方必须等待远程描述
  187. if (!this.peerConnection.remoteDescription && !this.isCaller) {
  188. this.pendingIceCandidates.push(candidate);
  189. return;
  190. }
  191. await this.peerConnection.addIceCandidate(candidate);
  192. console.log("✅ 成功添加 ICE 候选:", candidate.candidate);
  193. } catch (error) {
  194. console.error("❌ 添加 ICE 候选失败:", error);
  195. // 失败后重试缓存
  196. this.pendingIceCandidates.push(candidate);
  197. }
  198. },
  199. // 清理资源:挂断
  200. cleanup() {
  201. if (this.peerConnection) {
  202. this.peerConnection.close();
  203. this.peerConnection = null;
  204. }
  205. if (this.localStream) {
  206. this.localStream.getTracks().forEach((track) => track.stop());
  207. this.localStream = null;
  208. }
  209. if (this.remoteStream) {
  210. this.remoteStream.getTracks().forEach((track) => track.stop());
  211. this.remoteStream = null;
  212. }
  213. this.iceCandidates = [];
  214. this.connectionState = "disconnected";
  215. },
  216. },
  217. });