> ## Documentation Index
> Fetch the complete documentation index at: https://docs.vivix.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 对话与打断

让角色结合用户消息、Persona 和对话历史生成回答。首先[连接播放器](https://docs.vivix.ai/cn/streaming-avatar/integrate/trtc.md)。控制事件使用播放器示例提供的 `window.player.ws`。请根据 TRTC 或 Agora 播放器选择对应的麦克风代码。

## 1. 发送文本并请求回答

```json theme={null}
{
  "type": "conversation.item.create",
  "event_id": "message_1",
  "item": {
    "id": "user_1",
    "type": "message",
    "role": "user",
    "content": [
      {
        "type": "input_text",
        "text": "Can you help me choose a gift?"
      }
    ]
  }
}
```

每条消息都使用新的 `item.id`。等待 `conversation.item.created`，并确认其中的 `item.id` 等于 `user_1`，然后发送：

```json theme={null}
{
  "type": "response.create"
}
```

WebSocket 连接成功后，通过 `window.player.ws.send(JSON.stringify(event))` 发送这些事件。等待对应的 `conversation.item.created` 事件，可以确保回答中包含刚发送的新消息。

## 2. 显示回答

```javascript theme={null}
window.player.ws.addEventListener("message", ({ data }) => {
  const event = JSON.parse(data);
  if (event.type === "response.output_text.delta") {
    console.log(event.response_id, event.delta);
  }
});
```

按 `response_id` 累积 `delta`，并与 `response.output_text.done` 中的完整文本进行核对。根据实际的 `response.done` 状态结束 UI，包括失败和取消状态。文本生成完成并不代表音频播放已经完成。

## 3. 启用麦克风

这里使用普通语音对话：角色识别语音并生成回答。请勿为此启用 A2A passthrough。根据所用播放器选择一份代码，不要同时添加两个版本。将以下按钮添加到 index.html：

```html theme={null}
<button id="mic-on">Microphone on</button>
<button id="mic-off">Microphone off</button>
```

### TRTC

将以下代码添加到 TRTC 播放器的 main.js：

```javascript wrap theme={null}
const micOn = document.querySelector("#mic-on");
const micOff = document.querySelector("#mic-off");
micOn.onclick = async () => {
  try {
    if (!window.player?.trtc) throw new Error("Start the TRTC player first");
    await window.player.trtc.startLocalAudio();
  } catch (e) { document.querySelector("#status").textContent = e.message; }
};
micOff.onclick = async () => {
  try { await window.player?.trtc?.stopLocalAudio(); }
  catch (e) { document.querySelector("#status").textContent = e.message; }
};
```

### Agora

将以下代码添加到已经导入 AgoraRTC 的 Agora 播放器 main.js：

```javascript wrap theme={null}
// In the Agora player's main.js, which already imports AgoraRTC.
let microphone, microphoneClient;
let micBusy = false;
let desiredMic = false;
let micGeneration = 0;
const micOn = document.querySelector("#mic-on");
const micOff = document.querySelector("#mic-off");
micOn.onclick = async () => {
  if (microphone || micBusy) return;
  const client = window.player?.agora;
  if (!client) return;
  desiredMic = true;
  const generation = ++micGeneration;
  const stillWanted = () => desiredMic && generation === micGeneration
    && window.player?.agora === client;
  micBusy = true;
  let track;
  let published = false;
  try {
    track = await AgoraRTC.createMicrophoneAudioTrack();
    if (!stillWanted()) return;
    await client.publish([track]);
    published = true;
    if (!stillWanted()) return;
    microphone = track;
    microphoneClient = client;
    track = undefined; // Ownership passes to stopMicrophone().
  } catch (e) {
    document.querySelector("#status").textContent = e.message;
  } finally {
    try {
      if (track && published) await client.unpublish([track]);
    } catch (e) {
      document.querySelector("#status").textContent = e.message;
    } finally {
      track?.close();
      micBusy = false;
    }
  }
};
async function stopMicrophone() {
  desiredMic = false;
  ++micGeneration; // Also cancels capture awaiting permission or publication.
  const track = microphone;
  const client = microphoneClient;
  microphone = microphoneClient = undefined;
  if (!track) return;
  try { await client.unpublish([track]); }
  finally { track.close(); }
}
micOff.onclick = () => stopMicrophone().catch(e => {
  document.querySelector("#status").textContent = e.message;
});
```

关闭麦克风时，还会取消正在等待用户授权或等待发布的任务，并在音轨创建完成后将其关闭。在 Agora 播放器已有的 Stop 处理函数中，应先调用 `await stopMicrophone()`，再离开频道。无论使用哪个版本，修改后都需要重新构建 main.js 并刷新页面。请使用 HTTPS 或 localhost，并通过用户点击按钮来请求麦克风权限。默认的轮次检测会自动开始生成回答；不要为同一轮输入再次发送 `response.create`。如果用户拒绝授权，仍应保留文本输入方式。

## 4. 打断或排队播放下一段内容

```json theme={null}
{
  "type": "response.cancel"
}
```

该事件会取消当前正在生成的响应，并清除等待中的任务。如果当前没有活动响应，则会返回错误。取消后仍可能收到终态事件；请根据事件的实际状态更新 UI。

```json theme={null}
{
  "type": "response.create",
  "response": {
    "scheduling_policy": "after_current_response",
    "script": {
      "vocal": {
        "type": "speech",
        "text": "Next, let us look at the second option."
      }
    }
  }
}
```

新请求默认使用 `interrupt`，它会打断当前输出并清除等待中的任务。`after_current_response` 会等待当前响应结束；同一时间最多允许一个请求处于等待状态。`reject_if_busy` 会在系统忙碌时返回错误，可用于避免按钮被重复触发。等待中的请求会保留提交时捕获的输入和配置；之后发生的图片或配置变更不会重写该请求。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.