---
title: "無介面 Hook"
description: "使用 useThunderPhone React Hook 建立完全自訂的語音介面"
---

`useThunderPhone` 掛鈎函式讓你完全掌控使用者介面，同時由 ThunderPhone 管理語音工作階段、音訊路由及連線狀態。如你需要完全自訂的 UI——包括自訂按鈕、版面配置、動畫及品牌元素——同時由 ThunderPhone 在幕後處理一切，可使用此函式。

## 何時使用無介面掛鈎函式

預建的 `ThunderPhoneWidget` 元件可涵蓋大部分使用情境，但如你需要以下功能，請使用無介面掛鈎函式：

- 與你的應用程式設計系統一致的完全自訂通話 UI
- 由即時音訊水平驅動的音訊反應視覺效果（波形、球體、脈動指示器）
- 自訂通話流程，例如通話前表單、通話後問卷，或與語音並列的內嵌聊天
- 整合至現有元件程式庫（Material UI、Chakra、Radix 等）

---

## 安裝

```bash
npm install @thunderphone/widget
```

<Note>
  無介面掛鈎函式**不需要**匯入 `@thunderphone/widget/style.css`，因為你會提供自己的 UI。不過，你仍必須安裝相同的 `@thunderphone/widget` 套件。
</Note>

---

## 基本用法

```tsx
import { useThunderPhone } from '@thunderphone/widget'

function CustomCallButton() {
  const phone = useThunderPhone({
    publishableKey: 'pk_live_your_publishable_key',
  })

  const handleClick = () => {
    if (phone.state === 'connected') {
      phone.disconnect()
    } else {
      phone.connect()
    }
  }

  return (
    <>
      <button onClick={handleClick} disabled={phone.state === 'connecting'}>
        {phone.state === 'connecting'
          ? 'Connecting...'
          : phone.state === 'connected'
            ? 'End call'
            : 'Start call'}
      </button>
      {phone.audio}
    </>
  )
}
```

<Warning>
  **你必須在元件樹的某處渲染 `phone.audio`。** 這是一個不可見的 React 元素，負責管理底層音訊連線。如省略此元素，將無法播放音訊，工作階段亦無法運作。
</Warning>

---

## 選項

透過 `UseThunderPhoneOptions` 將以下選項傳遞至 `useThunderPhone`：

| 選項 | 類型 | 必需 | 預設值 | 說明 |
|--------|------|----------|---------|-------------|
| `publishableKey` | `string` | 是 | -- | 可公開的 API 金鑰（`pk_live_...`）。系統會根據該金鑰的 Widget 設定自動解析智能體。 |
| `apiBase` | `string` | 否 | `'https://api.thunderphone.com/v1'` | 覆寫 API 基礎 URL。 |
| `language` | `string` | 否 | -- | 每個工作階段的語言覆寫設定——可使用語言代碼或地區設定，例如 `en`、`es` 或 `fr-FR`。未設定時，會套用智能體已設定的語言。 |
| `voice` | `string` | 否 | -- | 每個工作階段的語音覆寫設定——可使用語音名稱，例如 `maria`。未設定時，會套用智能體已設定的語音。 |
| `context` | `string` | 否 | -- | 傳遞至智能體的每個工作階段事實性頁面或網站內容。伺服器端會截斷至 12,000 個字元。 |
| `onConnect` | `() => void` | 否 | -- | 語音工作階段連線時呼叫。 |
| `onDisconnect` | `() => void` | 否 | -- | 工作階段結束時呼叫。 |
| `onError` | `(error) => void` | 否 | -- | 發生錯誤時呼叫。錯誤包含 `error`（代碼）及 `message` 欄位。 |
| `ringtone` | `boolean \| string` | 否 | `false` | 連線期間播放鈴聲。`true` 使用預設鈴聲，或使用 URL 字串指定自訂音訊。 |

<Note>
  此掛鈎函式為無介面模式：它**不會**接受 `ThunderPhoneWidget` 外觀屬性（`theme`、`primaryColor`、`title`、`position`、`className`）。傳遞這些屬性會導致 TypeScript 錯誤——介面呈現完全由你建立。
</Note>

---

## 回傳值

此 Hook 會回傳一個 `UseThunderPhoneReturn` 物件：

| 屬性 | 類型 | 說明 |
|----------|------|-------------|
| `state` | `'idle' \| 'connecting' \| 'connected' \| 'disconnected' \| 'error'` | 目前的連線狀態。 |
| `connect` | `() => void` | 開始語音工作階段。 |
| `disconnect` | `() => void` | 結束目前工作階段。 |
| `toggleMute` | `() => void` | 切換咪高峰靜音開關。 |
| `isMuted` | `boolean` | 咪高峰目前是否已靜音。 |
| `error` | `string \| undefined` | 當狀態為 `'error'` 時的錯誤訊息。 |
| `agentName` | `string \| undefined` | 已連線智能體的顯示名稱。 |
| `audioLevel` | `number` | **已棄用——永遠為 `0`**。為維持向後相容而保留的靜態佔位值；不會更新。請改為讀取 `audioLevelRef.current`。 |
| `audioLevelRef` | `React.RefObject<number>` | 包含即時音訊音量（0--1）的可變 ref——取智能體語音與訪客咪高峰中較高的音量——會在每個動畫畫格更新，並於 React 渲染週期以外執行。在 `requestAnimationFrame` 迴圈內讀取 `audioLevelRef.current`，以建立流暢、無卡頓的動畫；如需在 React state 中使用該值，則可按固定時間間隔擷取。 |
| `audio` | `ReactNode` | 處理音訊連線的不可見元素——**必須渲染**。 |

---

## 音訊反應式 UI

`audioLevelRef` ref 可讓你取得以畫面更新率提供的音訊電平，而不會觸發 React 重新渲染，最適合用於驅動流暢的波形視覺效果、脈動光球，或任何與對話連動的動畫。電平會反映較大聲的一方：智能體的聲音或訪客的咪高峰。

### 波形範例

```tsx
import { useRef, useEffect } from 'react'
import { useThunderPhone } from '@thunderphone/widget'

function WaveformCall() {
  const phone = useThunderPhone({
    publishableKey: 'pk_live_your_publishable_key',
  })
  const canvasRef = useRef<HTMLCanvasElement>(null)

  useEffect(() => {
    if (phone.state !== 'connected') return
    const canvas = canvasRef.current
    if (!canvas) return
    const ctx = canvas.getContext('2d')!

    let animId: number
    const draw = () => {
      const level = phone.audioLevelRef.current ?? 0
      ctx.clearRect(0, 0, canvas.width, canvas.height)

      // Draw bars that react to audio level
      const barCount = 24
      const barWidth = canvas.width / barCount
      for (let i = 0; i < barCount; i++) {
        const distance = Math.abs(i - barCount / 2) / (barCount / 2)
        const height = level * canvas.height * (1 - distance * 0.6)
        const y = (canvas.height - height) / 2
        ctx.fillStyle = '#0ea5e9'
        ctx.fillRect(i * barWidth + 1, y, barWidth - 2, height)
      }

      animId = requestAnimationFrame(draw)
    }
    animId = requestAnimationFrame(draw)
    return () => cancelAnimationFrame(animId)
  }, [phone.state, phone.audioLevelRef])

  return (
    <div>
      {phone.state === 'connected' && (
        <canvas ref={canvasRef} width={240} height={80} />
      )}
      <button
        onClick={phone.state === 'connected' ? phone.disconnect : phone.connect}
        disabled={phone.state === 'connecting'}
      >
        {phone.state === 'connected' ? 'End call' : 'Start call'}
      </button>
      {phone.audio}
    </div>
  )
}
```

### 脈動光球範例

```tsx
import { useRef, useEffect } from 'react'
import { useThunderPhone } from '@thunderphone/widget'

function PulsingOrb() {
  const phone = useThunderPhone({
    publishableKey: 'pk_live_your_publishable_key',
  })
  const orbRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (phone.state !== 'connected') return
    let animId: number
    const animate = () => {
      const level = phone.audioLevelRef.current ?? 0
      if (orbRef.current) {
        const scale = 1 + level * 0.5
        orbRef.current.style.transform = `scale(${scale})`
        orbRef.current.style.opacity = `${0.6 + level * 0.4}`
      }
      animId = requestAnimationFrame(animate)
    }
    animId = requestAnimationFrame(animate)
    return () => cancelAnimationFrame(animId)
  }, [phone.state, phone.audioLevelRef])

  return (
    <div style={{ textAlign: 'center' }}>
      <div
        ref={orbRef}
        style={{
          width: 80,
          height: 80,
          borderRadius: '50%',
          background: '#0ea5e9',
          margin: '20px auto',
          transition: 'transform 0.05s ease-out',
        }}
      />
      <button
        onClick={phone.state === 'connected' ? phone.disconnect : phone.connect}
        disabled={phone.state === 'connecting'}
      >
        {phone.state === 'connected' ? 'End call' : 'Call'}
      </button>
      {phone.audio}
    </div>
  )
}
```

### 說話指示器範例

如要建立會隨音量改變的 React 渲染 UI——例如以閾值為基礎的「說話中」標籤——請按固定時間間隔讀取 `audioLevelRef.current`，並將結果儲存至 state：

```tsx
import { useEffect, useState } from 'react'
import { useThunderPhone } from '@thunderphone/widget'

function SpeakingBadge() {
  const phone = useThunderPhone({
    publishableKey: 'pk_live_your_publishable_key',
  })
  const [speaking, setSpeaking] = useState(false)

  useEffect(() => {
    if (phone.state !== 'connected') {
      setSpeaking(false)
      return
    }
    const interval = setInterval(() => {
      setSpeaking((phone.audioLevelRef.current ?? 0) > 0.1)
    }, 100)
    return () => clearInterval(interval)
  }, [phone.state, phone.audioLevelRef])

  return (
    <div>
      {phone.state === 'connected' && (
        <span>{speaking ? 'Speaking' : 'Listening'}</span>
      )}
      <button onClick={phone.state === 'connected' ? phone.disconnect : phone.connect}>
        {phone.state === 'connected' ? 'End call' : 'Start call'}
      </button>
      {phone.audio}
    </div>
  )
}
```

<Warning>
  請始終從 `audioLevelRef.current` 讀取電平。回傳物件中的 `audioLevel` 數值已**棄用，並且永遠為 `0`**——任何基於此數值建立的邏輯都會在無提示下讀取零值。
</Warning>

---

## 狀態機

`state` 屬性遵循以下生命週期：

```
idle --> connecting --> connected --> disconnected --> idle (after 1.5s)
                  \
                   --> error (stays until connect() is called again)
```

| 狀態 | 說明 |
|-------|-------------|
| `idle` | 沒有進行中的工作階段。可隨時呼叫 `connect()`。 |
| `connecting` | 正在建立工作階段。此狀態期間請停用通話按鈕。 |
| `connected` | 語音工作階段進行中。使用者正在與智能體交談。 |
| `disconnected` | 工作階段已正常結束。1.5 秒後會自動轉回 `idle`。 |
| `error` | 發生錯誤。請查看 `phone.error` 取得訊息。此狀態**不會**自行清除——再次呼叫 `connect()` 會開始新的嘗試並重設錯誤。 |

---

## 範例

### 使用靜音控制

```tsx
import { useThunderPhone } from '@thunderphone/widget'

function CallWithMute() {
  const phone = useThunderPhone({
    publishableKey: 'pk_live_your_publishable_key',
  })

  return (
    <div>
      {phone.state === 'connected' && (
        <div>
          <p>Talking to {phone.agentName ?? 'Agent'}</p>
          <button onClick={phone.toggleMute}>
            {phone.isMuted ? 'Unmute' : 'Mute'}
          </button>
          <button onClick={phone.disconnect}>End call</button>
        </div>
      )}

      {phone.state !== 'connected' && (
        <button
          onClick={phone.connect}
          disabled={phone.state === 'connecting'}
        >
          {phone.state === 'connecting' ? 'Connecting...' : 'Call support'}
        </button>
      )}

      {phone.state === 'error' && (
        <p style={{ color: 'red' }}>{phone.error}</p>
      )}

      {phone.audio}
    </div>
  )
}
```

### 使用鈴聲

連接期間播放鈴聲，以模擬電話來電：

```tsx
import { useThunderPhone } from '@thunderphone/widget'

function PhoneCallButton() {
  const phone = useThunderPhone({
    publishableKey: 'pk_live_your_publishable_key',
    ringtone: true, // or a custom URL: 'https://example.com/ringtone.mp3'
  })

  return (
    <>
      <button
        onClick={phone.state === 'connected' ? phone.disconnect : phone.connect}
        disabled={phone.state === 'connecting'}
      >
        {phone.state === 'connecting'
          ? 'Ringing...'
          : phone.state === 'connected'
            ? 'Hang up'
            : 'Call'}
      </button>
      {phone.audio}
    </>
  )
}
```

鈴聲會在 `connecting` 狀態期間循環播放，並在智能體接通時淡出。傳入 `true` 可使用內置預設鈴聲，或傳入 URL 字串以使用你的音訊檔案。

### 使用事件回調

```tsx
import { useThunderPhone } from '@thunderphone/widget'

function TrackedCallButton() {
  const phone = useThunderPhone({
    publishableKey: 'pk_live_your_publishable_key',
    onConnect: () => {
      analytics.track('call_started')
    },
    onDisconnect: () => {
      analytics.track('call_ended')
    },
    onError: (error) => {
      analytics.track('call_error', { code: error.error, message: error.message })
    },
  })

  return (
    <>
      <button
        onClick={phone.state === 'connected' ? phone.disconnect : phone.connect}
        disabled={phone.state === 'connecting'}
      >
        {phone.state === 'connected' ? 'Hang up' : 'Talk to AI'}
      </button>
      {phone.audio}
    </>
  )
}
```

### 完全自訂 UI

```tsx
import { useThunderPhone } from '@thunderphone/widget'

function FullCustomUI() {
  const phone = useThunderPhone({
    publishableKey: 'pk_live_your_publishable_key',
  })

  return (
    <div className="call-panel">
      <div className="call-status">
        {phone.state === 'idle' && <span>Ready</span>}
        {phone.state === 'connecting' && <span className="pulse">Connecting...</span>}
        {phone.state === 'connected' && (
          <span>On call with {phone.agentName}</span>
        )}
        {phone.state === 'error' && <span className="error">{phone.error}</span>}
      </div>

      <div className="call-controls">
        {phone.state === 'connected' ? (
          <>
            <button className="mute-btn" onClick={phone.toggleMute}>
              {phone.isMuted ? 'Unmute' : 'Mute'}
            </button>
            <button className="end-btn" onClick={phone.disconnect}>
              End
            </button>
          </>
        ) : (
          <button
            className="start-btn"
            onClick={phone.connect}
            disabled={phone.state === 'connecting'}
          >
            Start call
          </button>
        )}
      </div>

      {/* Required -- handles audio under the hood */}
      {phone.audio}
    </div>
  )
}
```

---

## 提示

<AccordionGroup>
  <Accordion title="務必渲染 phone.audio">
    `phone.audio` 元素雖然不可見，但屬必要元素。可將其放置於 JSX 的任何位置——它不會渲染可見的 DOM，但會在內部管理 WebRTC 音訊連線。
  </Accordion>

  <Accordion title="連線期間停用按鈕">
    `connecting` 狀態可持續 1 至 3 秒。於此狀態期間停用通話按鈕，以防止重複嘗試連線。
  </Accordion>

  <Accordion title="妥善處理錯誤狀態">
    當狀態為 `error` 時，向使用者顯示 `phone.error`，並保持通話按鈕可用。此 hook 不會自行離開 `error` 狀態——再次呼叫 `connect()` 會開始全新嘗試，並清除先前的錯誤。
  </Accordion>

  <Accordion title="使用回呼函式處理副作用">
    `onConnect`、`onDisconnect` 及 `onError` 回呼函式非常適合用於分析、記錄日誌，或觸發其他應用程式邏輯，而無需輪詢狀態。
  </Accordion>

  <Accordion title="從 audioLevelRef 讀取音訊音量">
    `audioLevelRef` 是唯一的即時音訊音量來源。在 `requestAnimationFrame` 內讀取 `audioLevelRef.current`，可實現波形等流暢動畫（讀取 ref 不會導致重新渲染）；或者按固定間隔取樣，並將結果儲存於 state，供 React 渲染的 UI 使用。`audioLevel` 數值已被淘汰，且永遠為 `0`——請勿基於它建立邏輯。
  </Accordion>
</AccordionGroup>
