Spaces:
Sleeping

ttkkk / client.html
sunneytree
添加音色克隆功能
b05ee35
Raw History Blame Contribute Delete
28.5 kB
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CosyVoice WebSocket 客户端</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
margin: 0;
padding: 20px;
background-color: #f5f5f5;
color: #333;
}
.container {
max-width: 800px;
margin: 0 auto;
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
h1 {
color: #2c3e50;
margin-top: 0;
border-bottom: 1px solid #eee;
padding-bottom: 10px;
}
label {
display: block;
margin: 15px 0 5px;
font-weight: bold;
}
input, textarea, select {
width: 100%;
padding: 8px;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
}
button {
background-color: #3498db;
color: white;
border: none;
padding: 10px 15px;
border-radius: 4px;
cursor: pointer;
margin-right: 5px;
transition: background-color 0.3s;
}
button:hover {
background-color: #2980b9;
}
button:disabled {
background-color: #95a5a6;
cursor: not-allowed;
}
.status {
margin: 15px 0;
padding: 10px;
border-radius: 4px;
background-color: #f9f9f9;
border-left: 4px solid #3498db;
}
.error {
border-left-color: #e74c3c;
background-color: #fadbd8;
}
.success {
border-left-color: #2ecc71;
background-color: #d5f5e3;
}
.audio-controls {
margin: 15px 0;
}
.voice-list {
margin: 15px 0;
max-height: 200px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 4px;
padding: 10px;
}
.voice-item {
padding: 8px;
margin-bottom: 5px;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.2s;
}
.voice-item:hover {
background-color: #f5f5f5;
}
.voice-item.selected {
background-color: #e1f5fe;
border-left: 3px solid #03a9f4;
}
.tabs {
display: flex;
margin-bottom: 20px;
border-bottom: 1px solid #ddd;
}
.tab {
padding: 10px 20px;
cursor: pointer;
border-bottom: 2px solid transparent;
}
.tab.active {
border-bottom-color: #3498db;
font-weight: bold;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.record-controls {
display: flex;
align-items: center;
margin: 10px 0;
}
.record-button {
background-color: #e74c3c;
margin-right: 10px;
}
.record-button.recording {
animation: pulse 1.5s infinite;
}
@keyframes pulse {
0% { opacity: 1; }
50% { opacity: 0.6; }
100% { opacity: 1; }
}
.recording-status {
margin-left: 10px;
}
.audio-visualizer {
height: 60px;
width: 100%;
background-color: #f9f9f9;
margin: 10px 0;
border-radius: 4px;
overflow: hidden;
position: relative;
}
.visualizer-canvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="container">
<h1>CosyVoice WebSocket 客户端</h1>
<div class="tabs">
<div class="tab active" data-tab="tts">文本转语音</div>
<div class="tab" data-tab="upload">上传参考音频</div>
<div class="tab" data-tab="voices">已保存音色</div>
</div>
<!-- 文本转语音选项卡 -->
<div class="tab-content active" id="tts-tab">
<label for="serverUrl">服务器地址:</label>
<input type="text" id="serverUrl" value="wss://bluece-ttkkk.hf.space/ws">
<label for="voiceSelect">选择音色:</label>
<select id="voiceSelect">
<option value="">加载中...</option>
</select>
<button id="refreshVoices">刷新音色列表</button>
<label for="textToSpeak">要转换的文本:</label>
<textarea id="textToSpeak" rows="5" placeholder="请输入要转换为语音的文本..."></textarea>
<button id="speakButton">生成语音</button>
<button id="stopButton" disabled>停止</button>
<div class="audio-controls">
<audio id="audioPlayer" controls></audio>
</div>
<div class="status" id="statusMessage">准备就绪,请输入文本并选择音色。</div>
</div>
<!-- 上传参考音频选项卡 -->
<div class="tab-content" id="upload-tab">
<div class="audio-upload">
<label for="referenceText">参考文本:</label>
<textarea id="referenceText" rows="3" placeholder="请输入参考音频对应的文本内容..."></textarea>
<label for="voiceName">音色名称:</label>
<input type="text" id="voiceName" placeholder="请为这个音色取一个名字...">
<label>参考音频:</label>
<div class="record-controls">
<button id="recordButton" class="record-button">开始录音</button>
<span class="recording-status" id="recordingStatus">未录音</span>
</div>
<div class="audio-visualizer">
<canvas id="visualizer" class="visualizer-canvas"></canvas>
</div>
<div class="audio-controls">
<audio id="recordedAudio" controls></audio>
</div>
<input type="file" id="audioFile" accept="audio/*">
<button id="saveVoiceButton" disabled>保存音色</button>
<div class="status" id="uploadStatus">请录制或上传参考音频。</div>
</div>
</div>
<!-- 已保存音色选项卡 -->
<div class="tab-content" id="voices-tab">
<button id="listVoicesButton">获取已保存音色</button>
<div class="voice-list" id="savedVoicesList">
<p>点击"获取已保存音色"按钮查看列表。</p>
</div>
<div class="status" id="voicesStatus">准备就绪。</div>
</div>
</div>
<script>
// 全局变量
let ws = null;
let audioContext = null;
let mediaRecorder = null;
let audioChunks = [];
let isRecording = false;
let recordedBlob = null;
let visualizerCanvas = document.getElementById('visualizer');
let canvasContext = visualizerCanvas.getContext('2d');
let audioQueue = [];
let isPlaying = false;
let selectedVoiceId = '';
// DOM元素
const serverUrlInput = document.getElementById('serverUrl');
const voiceSelect = document.getElementById('voiceSelect');
const textToSpeak = document.getElementById('textToSpeak');
const speakButton = document.getElementById('speakButton');
const stopButton = document.getElementById('stopButton');
const audioPlayer = document.getElementById('audioPlayer');
const statusMessage = document.getElementById('statusMessage');
const tabs = document.querySelectorAll('.tab');
const tabContents = document.querySelectorAll('.tab-content');
const recordButton = document.getElementById('recordButton');
const recordingStatus = document.getElementById('recordingStatus');
const recordedAudio = document.getElementById('recordedAudio');
const audioFile = document.getElementById('audioFile');
const saveVoiceButton = document.getElementById('saveVoiceButton');
const uploadStatus = document.getElementById('uploadStatus');
const referenceText = document.getElementById('referenceText');
const voiceName = document.getElementById('voiceName');
const refreshVoicesButton = document.getElementById('refreshVoices');
const listVoicesButton = document.getElementById('listVoicesButton');
const savedVoicesList = document.getElementById('savedVoicesList');
const voicesStatus = document.getElementById('voicesStatus');
// 初始化
document.addEventListener('DOMContentLoaded', function() {
// 设置标签页切换
tabs.forEach(tab => {
tab.addEventListener('click', () => {
tabs.forEach(t => t.classList.remove('active'));
tabContents.forEach(c => c.classList.remove('active'));
tab.classList.add('active');
document.getElementById(`${tab.dataset.tab}-tab`).classList.add('active');
});
});
// 初始化音频上下文
try {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
audioContext = new AudioContext();
} catch (e) {
showStatus('您的浏览器不支持Web Audio API', true);
}
// 调整可视化器画布大小
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
// 连接WebSocket
connectWebSocket();
// 设置事件监听器
setupEventListeners();
});
function resizeCanvas() {
visualizerCanvas.width = visualizerCanvas.clientWidth;
visualizerCanvas.height = visualizerCanvas.clientHeight;
}
function setupEventListeners() {
// 连接按钮
serverUrlInput.addEventListener('change', connectWebSocket);
// 语音生成按钮
speakButton.addEventListener('click', generateSpeech);
stopButton.addEventListener('click', stopSpeech);
// 录音按钮
recordButton.addEventListener('click', toggleRecording);
// 文件上传
audioFile.addEventListener('change', handleFileUpload);
// 保存音色按钮
saveVoiceButton.addEventListener('click', saveVoice);
// 刷新音色列表按钮
refreshVoicesButton.addEventListener('click', fetchVoices);
// 获取已保存音色按钮
listVoicesButton.addEventListener('click', fetchVoices);
}
function connectWebSocket() {
// 关闭现有连接
if (ws) {
ws.close();
}
const serverUrl = serverUrlInput.value.trim();
if (!serverUrl) {
showStatus('请输入服务器地址', true);
return;
}
try {
ws = new WebSocket(serverUrl);
ws.onopen = function() {
showStatus('已连接到服务器');
fetchVoices();
};
ws.onclose = function() {
showStatus('与服务器的连接已关闭', true);
};
ws.onerror = function(error) {
showStatus('WebSocket错误: ' + error.message, true);
};
ws.onmessage = function(event) {
handleServerMessage(event.data);
};
} catch (error) {
showStatus('连接错误: ' + error.message, true);
}
}
function fetchVoices() {
if (!ws || ws.readyState !== WebSocket.OPEN) {
showStatus('未连接到服务器', true);
return;
}
// 发送获取语音列表请求
ws.send(JSON.stringify({
action: 'list_voices'
}));
showStatus('正在获取可用音色...');
}
function generateSpeech() {
if (!ws || ws.readyState !== WebSocket.OPEN) {
showStatus('未连接到服务器', true);
return;
}
const text = textToSpeak.value.trim();
if (!text) {
showStatus('请输入要转换的文本', true);
return;
}
const voiceId = voiceSelect.value;
if (!voiceId) {
showStatus('请选择音色', true);
return;
}
// 清空音频队列
audioQueue = [];
isPlaying = false;
// 发送TTS请求
ws.send(JSON.stringify({
action: 'tts',
text: text,
voice_id: voiceId
}));
speakButton.disabled = true;
stopButton.disabled = false;
showStatus('正在生成语音...');
}
function stopSpeech() {
// 清空音频队列
audioQueue = [];
isPlaying = false;
// 停止当前播放
audioPlayer.pause();
audioPlayer.currentTime = 0;
speakButton.disabled = false;
stopButton.disabled = true;
showStatus('已停止语音生成');
}
function handleServerMessage(data) {
try {
const message = JSON.parse(data);
switch (message.type) {
case 'start':
showStatus('开始生成语音...');
break;
case 'audio':
// 接收音频数据
handleAudioData(message.data, message.sample_rate);
break;
case 'end':
speakButton.disabled = false;
stopButton.disabled = true;
showStatus('语音生成完成');
break;
case 'error':
speakButton.disabled = false;
stopButton.disabled = true;
showStatus('错误: ' + message.message, true);
break;
case 'info':
showStatus(message.message);
break;
case 'voices':
updateVoicesList(message.data);
break;
case 'voice_saved':
saveVoiceButton.disabled = true;
showUploadStatus('音色保存成功! ID: ' + message.voice_id, false);
fetchVoices(); // 刷新音色列表
break;
default:
console.log('未知消息类型:', message);
}
} catch (error) {
console.error('处理服务器消息时出错:', error);
showStatus('处理服务器消息时出错', true);
}
}
function handleAudioData(base64Data, sampleRate) {
// 解码base64数据
const binaryString = atob(base64Data);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
// 创建音频Blob
const audioBlob = new Blob([bytes], { type: 'audio/wav' });
// 添加到音频队列
audioQueue.push(audioBlob);
// 如果没有在播放,开始播放
if (!isPlaying) {
playNextAudio();
}
}
function playNextAudio() {
if (audioQueue.length === 0) {
isPlaying = false;
return;
}
isPlaying = true;
const audioBlob = audioQueue.shift();
const audioUrl = URL.createObjectURL(audioBlob);
audioPlayer.src = audioUrl;
audioPlayer.play()
.then(() => {
// 音频播放结束后释放URL
audioPlayer.onended = function() {
URL.revokeObjectURL(audioUrl);
playNextAudio();
};
})
.catch(error => {
console.error('播放音频时出错:', error);
URL.revokeObjectURL(audioUrl);
playNextAudio();
});
}
function updateVoicesList(voices) {
// 更新下拉选择框
voiceSelect.innerHTML = '';
if (voices.length === 0) {
const option = document.createElement('option');
option.value = '';
option.textContent = '没有可用的音色';
voiceSelect.appendChild(option);
showStatus('没有可用的音色');
} else {
voices.forEach(voice => {
const option = document.createElement('option');
option.value = voice.ShortName;
option.textContent = `${voice.FriendlyName} (${voice.Gender}, ${voice.Locale})`;
voiceSelect.appendChild(option);
});
showStatus(`已加载 ${voices.length} 个音色`);
// 如果之前有选择的音色,尝试恢复选择
if (selectedVoiceId) {
voiceSelect.value = selectedVoiceId;
}
// 更新已保存音色列表
updateSavedVoicesList(voices);
}
}
function updateSavedVoicesList(voices) {
savedVoicesList.innerHTML = '';
if (voices.length === 0) {
savedVoicesList.innerHTML = '<p>没有保存的音色</p>';
voicesStatus.textContent = '没有保存的音色';
return;
}
voices.forEach(voice => {
const voiceItem = document.createElement('div');
voiceItem.className = 'voice-item';
voiceItem.dataset.voiceId = voice.ShortName;
voiceItem.innerHTML = `
<strong>${voice.FriendlyName}</strong>
<div>ID: ${voice.ShortName}</div>
<div>性别: ${voice.Gender}, 语言: ${voice.Locale}</div>
`;
voiceItem.addEventListener('click', function() {
// 移除其他选中项的高亮
document.querySelectorAll('.voice-item').forEach(item => {
item.classList.remove('selected');
});
// 高亮当前选中项
this.classList.add('selected');
// 设置选中的音色ID
selectedVoiceId = this.dataset.voiceId;
// 切换到TTS选项卡并设置选择框
tabs[0].click();
voiceSelect.value = selectedVoiceId;
});
savedVoicesList.appendChild(voiceItem);
});
voicesStatus.textContent = `共有 ${voices.length} 个保存的音色`;
}
async function toggleRecording() {
if (isRecording) {
// 停止录音
stopRecording();
} else {
// 开始录音
startRecording();
}
}
async function startRecording() {
try {
// 请求麦克风权限
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
// 设置可视化
setupAudioVisualization(stream);
// 创建MediaRecorder
mediaRecorder = new MediaRecorder(stream);
audioChunks = [];
mediaRecorder.ondataavailable = function(event) {
audioChunks.push(event.data);
};
mediaRecorder.onstop = function() {
// 创建音频Blob
recordedBlob = new Blob(audioChunks, { type: 'audio/wav' });
const audioUrl = URL.createObjectURL(recordedBlob);
// 设置音频播放器
recordedAudio.src = audioUrl;
recordedAudio.style.display = 'block';
// 启用保存按钮
saveVoiceButton.disabled = false;
};
// 开始录音
mediaRecorder.start();
isRecording = true;
// 更新UI
recordButton.textContent = '停止录音';
recordButton.classList.add('recording');
recordingStatus.textContent = '正在录音...';
} catch (error) {
console.error('录音时出错:', error);
showUploadStatus('无法访问麦克风: ' + error.message, true);
}
}
function stopRecording() {
if (mediaRecorder && isRecording) {
mediaRecorder.stop();
isRecording = false;
// 更新UI
recordButton.textContent = '开始录音';
recordButton.classList.remove('recording');
recordingStatus.textContent = '录音完成';
}
}
function setupAudioVisualization(stream) {
const audioSource = audioContext.createMediaStreamSource(stream);
const analyser = audioContext.createAnalyser();
analyser.fftSize = 256;
audioSource.connect(analyser);
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
canvasContext.clearRect(0, 0, visualizerCanvas.width, visualizerCanvas.height);
function draw() {
if (!isRecording) return;
requestAnimationFrame(draw);
analyser.getByteFrequencyData(dataArray);
canvasContext.fillStyle = '#f5f5f5';
canvasContext.fillRect(0, 0, visualizerCanvas.width, visualizerCanvas.height);
const barWidth = (visualizerCanvas.width / bufferLength) * 2.5;
let x = 0;
for (let i = 0; i < bufferLength; i++) {
const barHeight = (dataArray[i] / 255) * visualizerCanvas.height;
canvasContext.fillStyle = `rgb(50, ${dataArray[i] + 100}, 200)`;
canvasContext.fillRect(x, visualizerCanvas.height - barHeight, barWidth, barHeight);
x += barWidth + 1;
}
}
draw();
}
function handleFileUpload(event) {
const file = event.target.files[0];
if (!file) return;
// 检查文件类型
if (!file.type.startsWith('audio/')) {
showUploadStatus('请选择音频文件', true);
return;
}
// 读取文件
const reader = new FileReader();
reader.onload = function(e) {
// 创建音频Blob
recordedBlob = new Blob([e.target.result], { type: file.type });
const audioUrl = URL.createObjectURL(recordedBlob);
// 设置音频播放器
recordedAudio.src = audioUrl;
recordedAudio.style.display = 'block';
// 启用保存按钮
saveVoiceButton.disabled = false;
showUploadStatus('音频文件已加载');
};
reader.onerror = function() {
showUploadStatus('读取文件时出错', true);
};
reader.readAsArrayBuffer(file);
}
function saveVoice() {
if (!ws || ws.readyState !== WebSocket.OPEN) {
showUploadStatus('未连接到服务器', true);
return;
}
const refText = referenceText.value.trim();
if (!refText) {
showUploadStatus('请输入参考文本', true);
return;
}
const name = voiceName.value.trim();
if (!name) {
showUploadStatus('请输入音色名称', true);
return;
}
if (!recordedBlob) {
showUploadStatus('请先录制或上传音频', true);
return;
}
// 读取音频数据
const reader = new FileReader();
reader.onload = function(e) {
const audioData = e.target.result;
const base64Data = audioData.split(',')[1];
// 发送保存音色请求
ws.send(JSON.stringify({
action: 'save_voice',
audio_data: base64Data,
reference_text: refText,
voice_name: name
}));
showUploadStatus('正在保存音色...');
saveVoiceButton.disabled = true;
};
reader.onerror = function() {
showUploadStatus('读取音频数据时出错', true);
};
reader.readAsDataURL(recordedBlob);
}
function showStatus(message, isError = false) {
statusMessage.textContent = message;
statusMessage.className = isError ? 'status error' : 'status';
}
function showUploadStatus(message, isError = false) {
uploadStatus.textContent = message;
uploadStatus.className = isError ? 'status error' : 'status';
}
</script>
</body>
</html>