intelligentMusicProduction.vue 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. <template>
  2. <view class="dialog-generation">
  3. <view class="subject-matter-ofText" :style="{ paddingBottom: keyboardHeight + 'px' }">
  4. <!-- 顶部导航栏 -->
  5. <div class="navbar">
  6. <view class="navbar-left">
  7. <image @click="goBack()" class="back" src="../../static/vip/hy_icon_jiantou.png"></image>
  8. <view class="elf-name">精灵·小萌</view>
  9. <image class="deepseek" src="../../static/makedetail/deepseek-logo.png"></image>
  10. </view>
  11. <view class="navbar-right">
  12. <image @click="switchToNormal()" class="primary" src="../../static/makedetail/primary.png"></image>
  13. <image @click="newChar()" class="createChat" src="../../static/makedetail/createChat.png"></image>
  14. </view>
  15. </div>
  16. <!-- <view class="navbar-reserveASeat"> </view> -->
  17. <!-- 聊天内容区 -->
  18. <scroll-view class="chat-content" :scroll-into-view="toView" scroll-y scroll-with-animation="true"
  19. :style="{ height: stateType === 3 ? 'calc(100% - 180rpx)' : `calc(100% - ${370 + textareaHeight}rpx)` }"
  20. @scroll="onChatScroll">
  21. <template v-if="messages && messages.length > 0">
  22. <!-- <scroll-view class="chat-content" scroll-y> -->
  23. <view v-for="(msg, idx) in messages" :key="idx" :class="['chat-bubble', msg.role]">
  24. <template v-if="msg.role === 'user'">
  25. <uv-text size="32rpx" color="rgba(255, 255, 255, 0.7)" :text="msg.content"></uv-text>
  26. </template>
  27. <template v-else-if="msg.role === 'ai'">
  28. <view class="ai-bubble-row">
  29. <view class="ai-avatar">
  30. <image src="../../static/makedetail/characterProfilePicture.png" mode="aspectFill">
  31. </image>
  32. </view>
  33. <!-- 第一句话 -->
  34. <view v-if="msg.type == 0" class="ai-bubble-content">
  35. <view>欢迎来到萌创星球AI写歌🎉🎉🎉!这里能满足你创作音乐🎸、释放灵感🎵,创造独属于你的音乐旋律!
  36. </view>
  37. <br>
  38. <view>
  39. 可以根据自己的喜好点击下方的选项,快速开始创作🎼,
  40. </view>
  41. <div @click="onCateSent('纯音乐')" class="btn-box"> 纯音乐
  42. </div>
  43. <div @click="onCateSent('AI生成歌词')" class="btn-box" style="margin:0 20rpx"> AI生成歌词
  44. </div>
  45. <div @click="onCateSent('自定义歌词')" class="btn-box"> 自定义歌词
  46. </div>
  47. </view>
  48. <!-- 第二句话 -->
  49. <view class="ai-bubble-content" v-else-if="msg.type == 1">
  50. <text>{{ msg.content }}</text>
  51. </view>
  52. <!-- 第三句话 -->
  53. <view class="ai-bubble-content"
  54. style="border-radius: 12rpx 36rpx 36rpx 36rpx;border: 1px solid rgba(255,255,255,0.1);"
  55. v-else-if="msg.type == 2">
  56. <!-- <text>{{ msg.content }}</text> -->
  57. <view class="lyrics-input-title">
  58. <view>歌词</view>
  59. <view class="right-btn" :class="{'right-btn-active': isLyricConfirmActive}" @click="onLyricSent()" @touchstart="isLyricConfirmActive = true" @touchend="isLyricConfirmActive = false" @touchcancel="isLyricConfirmActive = false">确认</view>
  60. </view>
  61. <scroll-view scroll-y class="lyricsInputBox" style="">
  62. <textarea v-if="idx == (messages.length - 1 )" v-model="lyricData" class="lyric-editor" auto-height
  63. :adjust-position="false" placeholder="修改歌词..." maxlength="-1" />
  64. <uv-text v-else size="32rpx" color="rgba(255, 255, 255, 0.7)" :text="msg.content"></uv-text>
  65. </scroll-view>
  66. </view>
  67. <view class="ai-bubble-content" v-else-if="msg.type == 4">
  68. <view>请输入音乐的风格</view>
  69. <br>
  70. <view>
  71. 也可以根据自己的喜好点击下方的选项,快速开始创作🎼,
  72. </view>
  73. <div @click="openTagPopup()" class="btn-box">
  74. 选择标签
  75. </div>
  76. </view>
  77. <!-- <view class="ai-bubble-content" v-else-if="msg.type == 1">
  78. <template v-if="idx === lastAiIndex && isLoading">
  79. <text>{{ displayText }}</text>
  80. <text v-if="isLoading" class="loading-dot">...</text>
  81. </template>
  82. <template v-else>
  83. <text>{{ msg.content }}</text>
  84. </template>
  85. </view> -->
  86. <view v-else-if="msg.type == 20" class="ai-bubble-content">
  87. <text>OK!~小萌开始生成音乐啦!</text><br>
  88. <div v-if="msg.isStartGenerating && msg.startGeneratingId == 0" class="btn-box">
  89. 点击查看
  90. ({{ countdown }}) s</div>
  91. <div v-else
  92. @click="goPage(`/pages/makedetail/makeMusicDetail?id=${msg.startGeneratingId}`)"
  93. class="btn-box"> 点击查看
  94. </div>
  95. </view>
  96. </view>
  97. </template>
  98. </view>
  99. <view id="bottom-anchor"></view>
  100. <view v-if="error" class="chat-bubble ai error">{{ error }}</view>
  101. <view :style="{ height: stateType !== 3 || musicGenre == '自定义歌词' ? '200rpx' : '80rpx' }"></view>
  102. <image v-if="showToBottomBtn && keyboardHeight === 0" class="to-bottom-btn" @click="scrollToBottom"
  103. src="../../static/makedetail/toBottomBtn.png"></image>
  104. </template>
  105. <template v-else>
  106. <view class="chat-content-empty">
  107. <image src="../../static/makedetail/characterProfilePicture.png" mode="aspectFill"></image>
  108. <view class="chat-content-empty-title">嗨!我是创梦精灵</view>
  109. <view class="chat-content-empty-desc">与我聊聊你想要生成的角色吧!</view>
  110. </view>
  111. </template>
  112. </scroll-view>
  113. <!-- <view class="bom-reserveASeat"></view> -->
  114. <view v-if="stateType !== 3 || musicGenre == '自定义歌词'" class="bom-box"
  115. :style="{ bottom: 0 + 'px', height: `${190 + textareaHeight}rpx` }">
  116. <view class="bom-box-bg">
  117. <c-lottie ref="cLottieRef" :src='"/static/lottie/xiaomeng.json"' class="icon-img" height="108rpx"
  118. width="112rpx" :loop="true" :autoPlay="false"></c-lottie>
  119. </view>
  120. <!-- 底部输入区 -->
  121. <view class="input-bar">
  122. <!-- <image class="icon-img" src="../../static/makedetail/characterProfilePicture.png" mode="aspectFill">
  123. </image> -->
  124. <textarea :autoHeight="true" class="input-box" :adjust-position="false" v-model="question"
  125. :disabled="isLoading" placeholder="给我发送消息吧..." maxlength="400" @input="onTextareaInput"
  126. confirm-type="search" @confirm="onSend" rows="1"
  127. style="overflow-y:auto;max-height:176rpx;min-height:44rpx;" />
  128. <!-- <button class="send-btn" :disabled="isLoading || !question.trim()" @click="onSend">{{ isLoading ?
  129. '生成中...' :
  130. '发送' }}</button> -->
  131. <image v-if="isLoading" class="stop" src="../../static/makedetail/stop.png" mode=""
  132. @click="stopStreamAnswer" />
  133. <image v-else-if="!isLoading && !question.trim() && keyboardHeight === 0" class="keyboard"
  134. src="../../static/makedetail/keyboard.png" mode="" />
  135. <image v-else-if="!isLoading && question.trim() && keyboardHeight !== 0" class="send"
  136. src="../../static/makedetail/send.png" mode="" @click="onSend" />
  137. </view>
  138. <!-- 底部提示 -->
  139. <view class="footer-tip">内容由AI生成,禁用相关功能请联系管理员。</view>
  140. </view>
  141. </view>
  142. <DialogBox ref="DialogBox"></DialogBox>
  143. <multi-select-popup ref="tagPopup" :initial-options="tagOptions" @selection-confirmed="handleTagSelection"
  144. @popup-closed="handlePopupClosed"></multi-select-popup>
  145. </view>
  146. </template>
  147. <script>
  148. import websocket from '@/common/websocket.js';
  149. import MultiSelectPopup from '@/components/MultiSelectPopup/MultiSelectPopup.vue';
  150. export default {
  151. components: {
  152. MultiSelectPopup
  153. },
  154. data() {
  155. return {
  156. question: '',
  157. answer: '',
  158. displayText: '',
  159. isComplete: false,
  160. isLoading: false,
  161. loadingText: '正在生成歌词,请稍候',
  162. loadingDots: '...',
  163. loadingTimer: null,
  164. error: null,
  165. retryCount: 0,
  166. maxRetries: 3,
  167. timer: null,
  168. lastResponseTime: 0,
  169. timeout: 30000,
  170. typingSpeed: 50,
  171. messages: [],
  172. lastAiIndex: -1,
  173. keyboardHeight: 0,
  174. statusBarHeight: 0,
  175. windowBottom: 0,
  176. toView: '',
  177. showToBottomBtn: false,
  178. textareaHeight: 0,
  179. isConnected: false,
  180. isStartGenerating: false,
  181. countdown: 0,
  182. stateType: 1,
  183. isLyricConfirmActive: false, // 用于歌词确认按钮的点击反馈
  184. stateTypeArray: ['clear', 'cate', 'getLyrics', 'setLyrics', 'getTags', 'setTags', 'setContent', '', '', '', '', 'setContent'],
  185. content: '',
  186. musicGenre: '',
  187. lyricData: '',
  188. tagsData: '',
  189. tagOptions: [], // 用于存储多选弹窗的选项
  190. // type = clear 清除|cate 第一句话选择 |getLyrics 获取歌词(需要上传描述)|setLyrics 修改歌词(再去判断是否有* 有重复没有下一步 没有展示标签)|setTags(修改标签) (下发一个static 失败有提示 成功就正常生成)|getTags 获取标签
  191. };
  192. },
  193. methods: {
  194. // /Work/streamAnswerMusicLast
  195. // /Work/streamAnswerMusic
  196. // {type:'',content:''}
  197. // type = clear 清除|cate 第一句话选择 |getLyrics 获取歌词(需要上传描述)|setLyrics 修改歌词(再去判断是否有* 有重复没有下一步 没有展示标签)|setTags(修改标签) (下发一个static 失败有提示 成功就正常生成)|getTags 获取标签
  198. formatMsgContent(content) {
  199. if (!content) return [];
  200. // 将换行符替换为 <br/>
  201. return content.replace(/\n/g, '<br/>');
  202. ;
  203. },
  204. scrollToBottom() {
  205. this.toView = '';
  206. this.$nextTick(() => {
  207. this.toView = 'bottom-anchor';
  208. });
  209. },
  210. async initWebSocket() {
  211. if (this.isConnected) return;
  212. try {
  213. // 发送初始化消息
  214. websocket.onOpen(() => {
  215. // setTimeout(() => {
  216. // websocket.send(JSON.stringify({ type: 'getTags', content: '' }));
  217. // }, 1000)
  218. });
  219. await websocket.connect('wss://e.zhichao.art/Gapi/Work/streamAnswerMusic', {
  220. uuid: getApp().globalData.uuid
  221. });
  222. this.isConnected = true;
  223. // 设置消息处理回调
  224. websocket.onMessage((data) => {
  225. console.log("data:", data);
  226. if (data && data.includes('{')) {
  227. var data = JSON.parse(data);
  228. }
  229. var type = data && data.type || '';
  230. var content = data && data.content || '';
  231. // type = error,
  232. // content=no_cate(首次分类没有设置)
  233. // content="歌词不合规,请重新输入"|"歌词中有违规禁词,请修改!"
  234. // type='lyrics',content=具体歌词
  235. // type=success,content='OKOKOK':提交成功
  236. // type=result,content=ID
  237. // 111111111111111111111111111111111
  238. // if (type === 'success' && content === 'OKOKOK') {
  239. // // 音乐生成开始,AI消息加载中提示
  240. // const aiMsg = this.messages[this.lastAiIndex];
  241. // if (aiMsg) {
  242. // aiMsg.isStartGenerating = true;
  243. // aiMsg.content = '音乐生成中,请稍候...';
  244. // }
  245. // this.isStartGenerating = true;
  246. // this.countdownFun(20);
  247. // }
  248. // if (type === 'result' && content) {
  249. // // 音乐生成中,显示跳转到音乐详情页按钮
  250. // const aiMsg = this.messages[this.lastAiIndex];
  251. // if (aiMsg) {
  252. // aiMsg.isStartGenerating = false;
  253. // aiMsg.startGeneratingId = content;
  254. // aiMsg.content = '音乐已生成,点击跳转到详情页';
  255. // }
  256. // }
  257. if (this.isLoading) {
  258. if (type == 'cate' && content == 'success') {
  259. // {"type":"setContent","content":content}
  260. // 此时 第第一步选择完成
  261. if (this.musicGenre == '纯音乐') {
  262. // 跳过获取 修改 歌词
  263. this.stateType = 11;
  264. this.messages.push({ role: 'ai', type: 1, content: '输入描述生成音乐' });
  265. }
  266. if (this.musicGenre == 'AI生成歌词') {
  267. this.messages.push({ role: 'ai', type: 1, content: '请描述歌词' });
  268. this.stateType = 2;
  269. }
  270. if (this.musicGenre == '自定义歌词') {
  271. this.messages.push({ role: 'ai', type: 1, content: '请输入歌词' });
  272. this.stateType = 3;
  273. }
  274. console.log(type, content);
  275. // {"type":"lyrics","content":"《古风之约》\n\n青山绿水间 桃花映人面\n清风拂衣袖 相思绕指尖\n亭台楼阁畔 琴声悠扬传\n往事如烟云 飘散在天边\n\n红墙绿瓦下 谁在等归雁\n明月照窗前 孤影难入眠\n一纸素笺上 写满了思念\n岁月如流水 匆匆又一年\n\n我与你共赴 这一场古风之约\n看那春花秋月 浪漫又缠绵\n执手相看泪眼 无语凝噎\n只愿与你相伴 直到永远\n\n我与你共赴 这一场古风之约\n听那琵琶弦上 倾诉着哀怨\n举杯对饮成三人 醉在花间\n只愿与你相守 岁岁年年"}
  276. }
  277. // if (data.includes('[DONE]')) {
  278. // // 结束生成
  279. // this.completeAnswer();
  280. // } else if (data.includes('ID:')) {
  281. // // 提取ID
  282. // const aiMsg = this.messages[this.lastAiIndex];
  283. // if (aiMsg) {
  284. // aiMsg.startGeneratingId = data.split(':')[1];
  285. // }
  286. // } else if (data.includes('OKOKOK')) {
  287. // const aiMsg = this.messages[this.lastAiIndex];
  288. // if (aiMsg) {
  289. // aiMsg.isStartGenerating = true;
  290. // }
  291. // this.isStartGenerating = true;
  292. // this.countdownFun(20);
  293. // } else {
  294. // const aiMsg = this.messages[this.lastAiIndex];
  295. // if (aiMsg) {
  296. // aiMsg.isStartGenerating = false;
  297. // this.displayText += data;
  298. // this.answer += data;
  299. // aiMsg.content += data;
  300. // this.retryCount = 0;
  301. // this.lastResponseTime = Date.now();
  302. // this.scrollToBottom();
  303. // }
  304. // }
  305. this.isLoading = false;
  306. }
  307. if (type == 'lyrics' && content) {
  308. console.log('获取到歌词', content);
  309. // 替换加载中的消息
  310. const lastMessageIndex = this.messages.length - 1;
  311. // 替换加载中的消息
  312. this.stopLoadingAnimation();
  313. // Find and remove the loading message
  314. for (let i = this.messages.length - 1; i >= 0; i--) {
  315. if (this.messages[i].isGeneratingLyrics) {
  316. this.messages.splice(i, 1);
  317. break;
  318. }
  319. }
  320. // 移除 isProcessing 的消息
  321. for (let i = this.messages.length - 1; i >= 0; i--) {
  322. if (this.messages[i].isProcessing) {
  323. this.messages.splice(i, 1);
  324. break;
  325. }
  326. }
  327. this.messages.push({ role: 'ai', type: 2, content: content });
  328. this.stateType = 3;
  329. this.lyricData = content;
  330. console.log(this.messages, 24);
  331. }
  332. if (type == 'tags' && content) {
  333. // 移除 isProcessing 的消息
  334. for (let i = this.messages.length - 1; i >= 0; i--) {
  335. if (this.messages[i].isProcessing) {
  336. this.messages.splice(i, 1);
  337. break;
  338. }
  339. }
  340. // 此时歌词合法 下一步获取标签
  341. this.stateType = 4;
  342. this.messages.push({ role: 'ai', type: 4, content: '请输入标签' });
  343. }
  344. // if (type == 'getTags' && content && !this.tagsData) { //确保只处理一次
  345. // // 获取标签成功
  346. // this.tagsData = JSON.parse(content);
  347. // console.log('获取到标签', this.tagsData);
  348. // // 将获取到的标签数据转换为 MultiSelectPopup 需要的格式
  349. // this.tagOptions = this.formatTagOptions(this.tagsData);
  350. // }
  351. // {"type":"success","content":"OKOKOK"}
  352. // {"type":"result","content":"208"}
  353. if (type == 'success' && (content == 'OKOKOK' || content == 'OK')) {
  354. // 音乐生成开始,AI消息加载中提示
  355. this.messages.push({ role: 'ai', type: 20, content: '', isStartGenerating: true, startGeneratingId: 0 });
  356. this.isStartGenerating = true;
  357. this.countdownFun(3);
  358. this.startLoadingAnimation();
  359. }
  360. if (type == 'result' && content) {
  361. // 生成完成,AI消息中显示立即查看按钮
  362. this.stopLoadingAnimation();
  363. const aiMsg = this.messages.find(msg => msg.isStartGenerating);
  364. if (aiMsg) {
  365. aiMsg.isStartGenerating = false;
  366. aiMsg.startGeneratingId = content;
  367. }
  368. this.isStartGenerating = false;
  369. }
  370. if (type == 'error' && content) {
  371. uni.showToast({
  372. title: content,
  373. icon: 'none'
  374. })
  375. }
  376. this.scrollToBottom();
  377. });
  378. // 设置错误处理回调
  379. websocket.onError((error) => {
  380. console.error('WebSocket错误:', error);
  381. this.isConnected = false;
  382. this.handleError(error);
  383. });
  384. // 设置关闭处理回调
  385. websocket.onClose(() => {
  386. console.log('WebSocket已关闭');
  387. this.isConnected = false;
  388. this.isLoading = false;
  389. });
  390. } catch (error) {
  391. console.error('WebSocket初始化失败:', error);
  392. this.isConnected = false;
  393. this.handleError(error);
  394. }
  395. },
  396. async startStreamAnswer(content) {
  397. if (!content.trim()) {
  398. uni.showToast({
  399. title: '请输入问题',
  400. icon: 'none'
  401. });
  402. return;
  403. }
  404. // 检查连接状态,如果断开则重连
  405. if (!this.isConnected) {
  406. try {
  407. await this.initWebSocket();
  408. } catch (error) {
  409. console.error('重连失败:', error);
  410. uni.showToast({
  411. title: '连接已断开,请重试',
  412. icon: 'none'
  413. });
  414. return;
  415. }
  416. }
  417. console.log('发送消息:', content);
  418. this.resetState();
  419. if (this.stateTypeArray[this.stateType] != 'setLyrics' || this.musicGenre == '自定义歌词') {
  420. this.messages.push({ role: 'user', content });
  421. }
  422. try {
  423. this.isLoading = true;
  424. if (false) {
  425. let aiMsg = {
  426. role: 'ai',
  427. content: '',
  428. isStartGenerating: false,
  429. startGeneratingId: 0
  430. };
  431. this.messages.push(aiMsg);
  432. this.lastAiIndex = this.messages.length - 1;
  433. this.content = content;
  434. }
  435. // 发送消息
  436. const messageType = this.stateTypeArray[this.stateType];
  437. let messageToSend = { type: messageType, content: content };
  438. // 特殊处理 stateType 11 (纯音乐描述)
  439. if (this.stateType === 11) {
  440. messageToSend = { type: 'setContent', content: content };
  441. }
  442. websocket.send(JSON.stringify(messageToSend));
  443. // 如果是获取歌词,则显示加载中
  444. if (messageType === 'getLyrics') {
  445. this.messages.push({ role: 'ai', type: 1, content: this.loadingText + this.loadingDots, isGeneratingLyrics: true });
  446. this.startLoadingAnimation();
  447. this.scrollToBottom();
  448. } else if (messageType === 'setLyrics') {
  449. this.messages.push({ role: 'ai', type: 1, content: '正在处理中...', isProcessing: true });
  450. this.scrollToBottom();
  451. }
  452. } catch (error) {
  453. console.error('发送消息失败:', error);
  454. this.handleError(error);
  455. }
  456. },
  457. onSend() {
  458. if (!this.question.trim() || this.isLoading) return;
  459. if (this.stateType === 4) { // 当前状态是等待输入标签
  460. const userTagInput = this.question.trim();
  461. this.messages.push({ role: 'user', content: userTagInput });
  462. websocket.send(JSON.stringify({ type: 'setTags', content: userTagInput }));
  463. // this.messages.push({ role: 'ai', type: 1, content: `好的,已选择标签:${userTagInput}` });
  464. this.question = '';
  465. this.scrollToBottom();
  466. return; // 阻止后续的 startStreamAnswer 调用
  467. }
  468. this.startStreamAnswer(this.question);
  469. this.question = '';
  470. },
  471. // 发送第一步指令
  472. onCateSent(content) {
  473. if (this.isLoading || this.musicGenre) return;
  474. this.startStreamAnswer(content);
  475. this.musicGenre = content;
  476. },
  477. // 发送歌词逻辑
  478. onLyricSent() {
  479. if (this.isLoading) return;
  480. if (this.lyricData.includes('*')) {
  481. uni.showToast({
  482. title: '歌词有"*",请修改后再保存',
  483. icon: 'none'
  484. });
  485. return;
  486. }
  487. this.messages[this.messages.length - 1].content = this.lyricData;
  488. this.startStreamAnswer(this.lyricData);
  489. },
  490. // 打开标签选择弹窗
  491. openTagPopup() {
  492. this.$refs.tagPopup.openPopup();
  493. },
  494. formatTagOptions(tagsData) {
  495. console.log('格式化标签选项', tagsData);
  496. // tagsData 的预期格式:
  497. // [
  498. // { "name": "情感", "children": [ { "name": "欢快", "children": [] }, ... ] },
  499. // ...
  500. // ]
  501. // 需要转换为 MultiSelectPopup 需要的格式:
  502. // [
  503. // { label: '情感', expanded: true, children: [{ label: '欢快', value: '欢快', selected: false }, ...] },
  504. // ...
  505. // ]
  506. if (!Array.isArray(tagsData)) return [];
  507. return tagsData.map(parentTag => ({
  508. label: parentTag.name,
  509. expanded: true, // 默认展开父选项
  510. children: parentTag.children.map(childTag => ({
  511. label: childTag.name,
  512. value: childTag.name, // 通常value和label相同,或根据实际情况设置
  513. selected: false
  514. }))
  515. }));
  516. },
  517. handleTagSelection(selectedValues) {
  518. console.log('选中的标签:', selectedValues);
  519. // 处理选中的标签,例如发送到后端
  520. // 示例:将选中的标签数组转换为字符串发送
  521. const tagsString = selectedValues.join(',');
  522. websocket.send(JSON.stringify({ type: 'setTags', content: tagsString }));
  523. // 可以在这里添加AI回复,告知用户标签已选择,正在生成音乐等
  524. // this.messages.push({ role: 'ai', type: 1, content: `好的,已选择标签:${tagsString},小萌开始生成音乐啦!` });
  525. this.scrollToBottom();
  526. },
  527. handlePopupClosed() {
  528. // 如果用户关闭了弹窗但没有选择任何标签,可以提供一个默认行为或提示
  529. // 例如,如果没有选择标签,可以发送一个空数组或特定指令
  530. },
  531. startLoadingAnimation() {
  532. let dotCount = 1;
  533. this.loadingTimer = setInterval(() => {
  534. dotCount++;
  535. if (dotCount > 3) {
  536. dotCount = 1;
  537. }
  538. this.loadingDots = '.'.repeat(dotCount);
  539. // Update the loading message content if it exists
  540. const loadingMessage = this.messages.find(msg => msg.isGeneratingLyrics);
  541. if (loadingMessage) {
  542. loadingMessage.content = this.loadingText + this.loadingDots;
  543. }
  544. }, 500); // 更新频率,例如每500毫秒
  545. },
  546. stopLoadingAnimation() {
  547. if (this.loadingTimer) {
  548. clearInterval(this.loadingTimer);
  549. this.loadingTimer = null;
  550. }
  551. this.loadingDots = '...'; // Reset to default
  552. },
  553. resetState() {
  554. this.answer = '';
  555. this.displayText = '';
  556. this.isComplete = false;
  557. this.error = null;
  558. this.retryCount = 0;
  559. this.lastResponseTime = Date.now();
  560. },
  561. handleError(error) {
  562. if (this.retryCount < this.maxRetries) {
  563. this.retryCount++;
  564. this.retryRequest();
  565. } else {
  566. this.error = '请求失败,请稍后重试';
  567. this.isLoading = false;
  568. this.stopLoadingAnimation();
  569. uni.showToast({
  570. title: this.error,
  571. icon: 'none'
  572. });
  573. }
  574. },
  575. retryRequest() {
  576. uni.showToast({
  577. title: `正在重试 (${this.retryCount}/${this.maxRetries})`,
  578. icon: 'none'
  579. });
  580. setTimeout(() => {
  581. this.startStreamAnswer(this.question);
  582. }, 1000 * this.retryCount);
  583. },
  584. completeAnswer() {
  585. this.isComplete = true;
  586. this.isLoading = false;
  587. this.stopLoadingAnimation();
  588. },
  589. stopStreamAnswer() {
  590. if (this.timer) {
  591. clearTimeout(this.timer);
  592. this.timer = null;
  593. }
  594. this.isLoading = false;
  595. this.stopLoadingAnimation();
  596. },
  597. checkTimeout() {
  598. if (Date.now() - this.lastResponseTime > this.timeout) {
  599. this.handleError(new Error('请求超时'));
  600. }
  601. },
  602. goBack() {
  603. uni.navigateBack({
  604. delta: 1
  605. });
  606. },
  607. onChatScroll(e) {
  608. const threshold = 800; // 离底部1.0417rem以内不显示按钮
  609. const {
  610. scrollHeight,
  611. scrollTop
  612. } = e.detail;
  613. const clientHeight = e.detail.clientHeight || e.detail.height || 0;
  614. if (scrollHeight - scrollTop - clientHeight > threshold) {
  615. this.showToBottomBtn = true;
  616. } else {
  617. this.showToBottomBtn = false;
  618. }
  619. },
  620. onTextareaInput(e) {
  621. console.log(e.detail);
  622. // 获取textarea的实际高度
  623. const query = uni.createSelectorQuery().in(this);
  624. query.select('.input-box').boundingClientRect(data => {
  625. if (data) {
  626. // 将px转换为rpx (假设设计稿是750rpx宽度)
  627. const height = (data.height * 750) / uni.getSystemInfoSync().windowWidth;
  628. // 减去基础高度90rpx,得到额外增加的高度
  629. this.textareaHeight = Math.max(0, height - 90);
  630. // 滚动到底部
  631. this.scrollToBottom();
  632. }
  633. }).exec();
  634. },
  635. retrieveHistoricalRecords() {
  636. uni.request({
  637. url: this.$apiHost + '/Work/streamAnswerMusicLast',
  638. method: 'GET',
  639. header: {
  640. 'content-type': 'application/json',
  641. 'sign': getApp().globalData.headerSign
  642. },
  643. data: {
  644. uuid: getApp().globalData.uuid,
  645. task_type: 2
  646. },
  647. success: (res) => {
  648. // step 0 未开始 1 已选择过第一次的选项 2 获取到歌词
  649. // cate 选择类型 lyrics 历史记录
  650. console.log("获取历史记录:", res.data);
  651. if (res.data.success === "yes") {
  652. this.messages = [];
  653. this.musicGenre = res.data.cate;
  654. // 未开始
  655. this.messages.push({ role: 'ai', type: 0, content: ' ' });
  656. if (res.data.step >= 1) {
  657. // 获取到歌词
  658. this.messages.push({ role: 'user', content: res.data.cate });
  659. }
  660. if (res.data.cate == '纯音乐') {
  661. // 跳过获取 修改 歌词
  662. this.messages.push({ role: 'ai', type: 1, content: '输入描述生成音乐' });
  663. this.stateType = 11;
  664. }
  665. if (res.data.cate == 'AI生成歌词') {
  666. this.messages.push({ role: 'ai', type: 1, content: '请描述歌词' });
  667. this.stateType = 2;
  668. }
  669. if (res.data.cate == '自定义歌词') {
  670. this.messages.push({ role: 'ai', type: 1, content: '请输入歌词' });
  671. this.stateType = 3;
  672. }
  673. if (res.data.content) {
  674. this.messages.push({ role: 'user', type: 1, content: res.data.content });
  675. }
  676. // AI生成歌词逻辑
  677. if (res.data.lyrics) {
  678. this.messages.push({ role: 'ai', type: 2, content:res.data.lyrics});
  679. this.stateType = 3;
  680. this.lyricData = res.data.lyrics;
  681. }
  682. } else {
  683. this.messages = []
  684. }
  685. console.log("获取历史记录:", this.messages);
  686. },
  687. fail: (err) => {
  688. console.log('获取历史记录失败', err);
  689. uni.showToast({
  690. title: '获取历史记录失败',
  691. icon: 'none'
  692. });
  693. }
  694. })
  695. },
  696. // 重新计算元素高度
  697. recalculateHeights() {
  698. // 重新计算textarea高度
  699. const query = uni.createSelectorQuery().in(this);
  700. query.select('.input-box').boundingClientRect(data => {
  701. if (data) {
  702. const height = (data.height * 750) / uni.getSystemInfoSync().windowWidth;
  703. this.textareaHeight = Math.max(0, height - 90);
  704. }
  705. }).exec();
  706. },
  707. countdownFun(n) {
  708. if (this.timer) {
  709. clearInterval(this.timer);
  710. }
  711. this.countdown = n;
  712. // 倒计时
  713. this.timer = setInterval(() => {
  714. this.countdown--;
  715. if (this.countdown <= 0) {
  716. clearInterval(this.timer);
  717. }
  718. }, 1000);
  719. },
  720. goPage(page) {
  721. uni.navigateTo({
  722. url: page,
  723. });
  724. },
  725. newChar() {
  726. this.$refs["DialogBox"]
  727. .confirm({
  728. title: "是否创建新对话",
  729. content: "立即结束当前对话内容,开启新的对话?",
  730. DialogType: "inquiry",
  731. btn1: "取消",
  732. btn2: "确定",
  733. animation: 0,
  734. })
  735. .then(() => {
  736. websocket.send(JSON.stringify({ type: 'clear', content: '' }));
  737. this.toView = ''
  738. this.showToBottomBtn = false
  739. this.textareaHeight = 0
  740. this.isConnected = false
  741. this.isStartGenerating = false
  742. this.countdown = 0
  743. this.stateType = 1
  744. this.stateTypeArray = ['clear', 'cate', 'getLyrics', 'setLyrics', 'getTags', 'setTags', 'setContent', '', '', '', '', 'setContent']
  745. this.content = ''
  746. this.musicGenre = ''
  747. this.lyricData = ''
  748. this.retrieveHistoricalRecords()
  749. });
  750. },
  751. switchToNormal() {
  752. this.$refs["DialogBox"]
  753. .confirm({
  754. title: "是否切回常规模式",
  755. content: "切换至普通常规模式进行创作?",
  756. DialogType: "inquiry",
  757. btn1: "取消",
  758. btn2: "确定",
  759. animation: 0,
  760. })
  761. .then(() => {
  762. this.goPage('/pages/makedetail/makeMusicDetail')
  763. });
  764. },
  765. getTags() {
  766. let that = this
  767. uni.request({
  768. url: this.$apiHost + '/Work/getTags',
  769. method: 'GET',
  770. header: {
  771. 'content-type': 'application/json',
  772. 'sign': getApp().globalData.headerSign
  773. },
  774. data: {
  775. uuid: getApp().globalData.uuid
  776. },
  777. success: (res) => {
  778. console.log("获取标签:", res.data);
  779. if (res.data && res.data.tags) {
  780. this.tagOptions = this.formatTagOptions(res.data.tags);
  781. }
  782. },
  783. fail: (err) => {
  784. console.log('获取标签失败:', err);
  785. uni.showToast({
  786. title: '获取标签失败',
  787. icon: 'none'
  788. });
  789. }
  790. })
  791. },
  792. },
  793. async created() {
  794. this.getTags();
  795. await this.initWebSocket();
  796. this.retrieveHistoricalRecords();
  797. this.timer = setInterval(() => {
  798. if (this.isLoading) {
  799. this.checkTimeout();
  800. }
  801. }, 1000);
  802. uni.onKeyboardHeightChange(res => {
  803. this.keyboardHeight = res.height;
  804. if (res.height === 0) {
  805. this.$refs.cLottieRef.call('stop')
  806. } else {
  807. this.$refs.cLottieRef.call('play')
  808. }
  809. this.$nextTick(() => {
  810. this.recalculateHeights();
  811. });
  812. });
  813. const systemInfo = uni.getSystemInfoSync();
  814. this.statusBarHeight = systemInfo.statusBarHeight;
  815. this.windowBottom = systemInfo.safeAreaInsets ? systemInfo.safeAreaInsets.bottom : 0;
  816. },
  817. beforeDestroy() {
  818. websocket.close();
  819. this.stopStreamAnswer();
  820. }
  821. }
  822. </script>
  823. <style lang="scss">
  824. @import './intelligentLifeChart.scss';
  825. .lyricsInputBox {
  826. width: 100%;
  827. height: calc(100vh - 455rpx);
  828. box-sizing: border-box;
  829. padding: 20rpx;
  830. }
  831. .lyrics-input-title {
  832. display: flex;
  833. justify-content: space-between;
  834. align-items: center;
  835. height: 35px;
  836. background: rgba(255, 255, 255, 0.1);
  837. border-radius: 12rpx 36rpx 0 0;
  838. padding-left: 20rpx;
  839. padding-right: 24rpx;
  840. font-size: 32rpx;
  841. .right-btn {
  842. font-size: 26rpx;
  843. background: rgba(255, 255, 255, 0.15);
  844. border-radius: 22rpx;
  845. border: 2rpx solid rgba(255, 255, 255, 0.15);
  846. padding: 4rpx 32rpx;
  847. transition: background-color 0.2s ease, transform 0.1s ease; // 添加过渡效果
  848. }
  849. .right-btn-active {
  850. background: rgba(255, 255, 255, 0.3); // 点击时的深色背景
  851. transform: scale(0.98); // 点击时的缩小效果
  852. }
  853. }
  854. .lyric-editor {
  855. width: 100%;
  856. background-color: transparent;
  857. border: none;
  858. padding: 0;
  859. margin-top: 10rpx;
  860. color: rgba(255, 255, 255, 0.7);
  861. font-size: 32rpx;
  862. }
  863. .to-bottom-btn {
  864. position: fixed;
  865. right: 50%;
  866. transform: translateX(50%);
  867. bottom: 20rpx;
  868. width: 60rpx;
  869. height: 60rpx;
  870. bottom: 220rpx;
  871. z-index: 999;
  872. opacity: .75;
  873. transition: opacity 0.2s;
  874. }
  875. .ai-bubble-row {
  876. display: flex;
  877. align-items: flex-start;
  878. }
  879. .ai-avatar {
  880. width: 60rpx;
  881. height: 60rpx;
  882. border-radius: 50%;
  883. margin-right: 20rpx;
  884. border: solid 2rpx rgb(238, 238, 238, .3);
  885. display: flex;
  886. align-items: flex-end;
  887. justify-content: center;
  888. image {
  889. width: 52rpx;
  890. height: 52rpx;
  891. }
  892. }
  893. .ai-bubble-content {
  894. flex: 1;
  895. }
  896. </style>