Shopify 商店如何整合語音 AI
How to Integrate Voice AI with Shopify Stores
教學示範如何把語音 AI 整合到 Shopify 商店,串接語音輸入與合成語音播放。流程涵蓋 ElevenLabs API 的文字轉語音(TTS)和聲音複製、語音轉文字(STT),並透過 Shopify API 取得商品資料。教學亦示範把 GPT-4、Claude 或 Rasa 等對話式 AI 平台接入語音聊天機械人。
Why Voice AI Matters for Shopify
Ever imagined a customer walking into your online store, saying “Show me the newest jackets” and instantly getting a voice‑guided tour? Voice AI isn’t a futuristic fantasy—it’s a proven way to increase engagement, boost conversions, and make your brand feel more human. For Shopify developers, integrating a voice assistant can be surprisingly straightforward once you know the right tools and flow.
Below, we’ll walk through a practical, developer‑friendly approach to adding voice AI to a Shopify store, covering text‑to‑speech (TTS), voice cloning, and how to tie everything together with Shopify’s APIs. The star of the show is ElevenLabs, a leading TTS provider that offers realistic voice cloning and low‑latency speech synthesis. We’ll use their API throughout this tutorial.
Prerequisites
| What you need | Why it matters |
|---|---|
| Shopify store (or a test store) | The target for your voice integration |
| Shopify API credentials (API key & password) | Needed for making GraphQL or REST calls |
| Node.js (v18+) | For the example JavaScript code |
| Python 3.8+ | Optional, for a quick TTS test |
| ElevenLabs account | Access to the TTS API and voice cloning |
| A microphone (for the front‑end demo) | To capture user speech |
Step 1: Create an ElevenLabs Account and Get Your API Key
- Sign up at ElevenLabs via the affiliate link below (you’ll receive a special offer and we’ll get a commission if you sign up—no extra cost to you!): https://try.elevenlabs.io/kr07zfuqn1bp
- In your dashboard, navigate to API Keys and copy your key.
- Keep it handy for the snippets that follow.
Step 2: Set Up a Simple Voice Prompt on Your Store
We’ll add a small “Voice” button to the product page that, when clicked, records the user’s voice, sends the text to ElevenLabs for TTS, and plays back the synthesized voice.
2.1 Add the Button in Liquid
<!-- product.liquid or product-template.liquid -->
<button id="voice-btn" style="margin-top: 10px;">
🎤 Talk to me
</button>
<audio id="voice-output" controls style="display: none;"></audio>
2.2 Front‑end JavaScript
// assets/voice.js
document.addEventListener('DOMContentLoaded', () => {
const btn = document.getElementById('voice-btn');
const audio = document.getElementById('voice-output');
btn.addEventListener('click', async () => {
// 1️⃣ Capture audio from the mic
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const mediaRecorder = new MediaRecorder(stream);
const chunks = [];
mediaRecorder.ondataavailable = e => chunks.push(e.data);
mediaRecorder.onstop = async () => {
const blob = new Blob(chunks, { type: 'audio/webm' });
const formData = new FormData();
formData.append('audio', blob, 'input.webm');
// 2️⃣ Transcribe with a simple speech‑to‑text service
// (You can replace this with Whisper, AssemblyAI, etc.)
const transcription = await transcribeAudio(formData);
// 3️⃣ Send the text to ElevenLabs TTS
const ttsUrl = 'https://api.elevenlabs.io/v1/text-to-speech/your-voice-id';
const ttsResponse = await fetch(ttsUrl, {
method: 'POST',
headers: {
'xi-api-key': 'YOUR_ELEVENLABS_API_KEY',
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: transcription,
voice_settings: { stability: 0.5, similarity_boost: 0.75 },
}),
});
const arrayBuffer = await ttsResponse.arrayBuffer();
const audioBlob = new Blob([arrayBuffer], { type: 'audio/mpeg' });
audio.src = URL.createObjectURL(audioBlob);
audio.style.display = 'block';
audio.play();
};
mediaRecorder.start();
// Stop after 5 seconds
setTimeout(() => mediaRecorder.stop(), 5000);
});
});
// Dummy transcription function – replace with real STT
async function transcribeAudio(formData) {
// Example using AssemblyAI
const resp = await fetch('https://api.assemblyai.com/v2/transcript', {
method: 'POST',
headers: {
'authorization': 'YOUR_ASSEMBLYAI_KEY',
'content-type': 'application/json',
},
body: JSON.stringify({ audio_url: 'URL_OF_THE_UPLOADED_AUDIO' }),
});
const data = await resp.json();
return data.text;
}
Tip: If you want a zero‑dependency solution, use the Web Speech API (
window.SpeechRecognition) for live transcription, but note browser support varies.
Step 3: Voice Cloning – Give Your Store a Custom Voice
ElevenLabs allows you to clone an existing voice or create a brand‑specific voice from a few minutes of audio. This is perfect for a “Shopify Store Assistant” that sounds like your brand.
3.1 Clone a Voice
curl -X POST "https://api.elevenlabs.io/v1/voice-cloning" \
-H "xi-api-key: YOUR_ELEVENLABS_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"audio_url": "https://example.com/your-voice-sample.wav",
"name": "MyStoreAssistant"
}'
The response will give you a voice_id. Use this ID in the TTS endpoint instead of the default voice.
3.2 Using the Cloned Voice in JavaScript
const ttsUrl = `https://api.elevenlabs.io/v1/text-to-speech/${voiceId}`;
Replace voiceId with the ID returned from the cloning step. Your store’s voice will now feel unique and consistent.
Step 4: Hook Into Shopify Events
You can use Shopify’s Storefront API (GraphQL) or Admin API to fetch product data, order status, or customer messages and feed that into the voice assistant.
4.1 Example: Fetch Product Description with GraphQL
const query = `
query GetProduct($handle: String!) {
productByHandle(handle: $handle) {
title
descriptionHtml
}
}
`;
async function fetchProduct(handle) {
const res = await fetch('/api/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query, variables: { handle } }),
});
const { data } = await res.json();
return data.productByHandle;
}
You can expose a lightweight /api/graphql proxy route in your Shopify app that forwards requests to the real Storefront API, keeping your API key secure.
Step 5: Build a Voice‑Enabled Chatbot
Combine the TTS pipeline with a conversational AI platform (e.g., OpenAI’s GPT‑4, Claude, or Rasa) to answer product questions, place orders, or offer personalized recommendations.
5.1 Basic Flow
- User speaks → capture audio.
- STT → convert to text.
- Chatbot → process text, generate reply.
- TTS (ElevenLabs) → synthesize reply.
- Play the synthesized audio back to the user.
You can orchestrate this in a Node.js Express route or a serverless function. Here’s a simplified snippet:
app.post('/voice-chat', async (req, res) => {
const { userText } = req.body; // already transcribed
// 1️⃣ Chatbot
const reply = await chatWithAI(userText); // e.g., OpenAI
// 2️⃣ TTS
const ttsRes = await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${voiceId}`, {
method: 'POST',
headers: {
'xi-api-key': 'YOUR_ELEVENLABS_API_KEY',
'Content-Type': 'application/json',
},
body: JSON.stringify({ text: reply }),
});
const audioBuf = await ttsRes.arrayBuffer();
res.set('Content-Type', 'audio/mpeg');
res.send(Buffer.from(audioBuf));
});
The front end can fetch /voice-chat and play the audio response in real time.
Deployment Tips
- Use Shopify’s App Bridge to embed your voice components inside the admin or POS experience.
- Cache TTS responses for frequently asked questions to reduce latency and API calls.
- Monitor usage: ElevenLabs offers detailed metrics; keep an eye on your quota.
Wrap‑Up
Adding voice AI to your Shopify store can feel like adding a new marketing channel, but it’s really a new layer of interaction. With ElevenLabs’ realistic TTS and voice‑cloning capabilities, you can:
- Offer instant product tours.
- Provide hands‑free shopping for users on the go.
- Create a memorable brand voice that feels personal.
The integration isn’t magic—just a few API calls, a bit of front‑end code, and a touch of creativity. Start experimenting today, and watch your customer engagement soar.
Ready to bring your Shopify store to life with voice?
Try ElevenLabs today and unlock the power of realistic speech synthesis and voice cloning for your e‑commerce experience: https://try.elevenlabs.io/kr07zfuqn1bp
來源:DEV Community · dev.to