إنشاء أداة Text-to-Voice متعددة اللغات لموقع أو مدونة

إنشاء Text-to-Voice متعددة اللغات لموقعك أو مدونتك

إنشاء أداة Text-to-Voice متعددة اللغات لموقع أو مدونة

المقدمة

في هذا المقال، سنتعلم كيفية إنشاء أداة تحويل النص إلى كلام (Text-to-Voice) تدعم عدة لغات باستخدام HTML وCSS وJavaScript وواجهة برمجة التطبيقات (API). هذه الأداة ستكون مفيدة لزوار موقعك أو مدونتك، خاصة لأولئك الذين يفضلون الاستماع إلى المحتوى بدلاً من قراءته. 

معاينة الصفحة text-to-voice

المتطلبات الأساسية

  1. معرفة أساسية بـ HTML وCSS وJavaScript
  2. حساب على أحد خدمات Text-to-Speech APIs (سنتستخدم SpeechSynthesis API المجانية أو API مدفوعة مثل Google Cloud Text-to-Speech)

الخطوة 1: إعداد الهيكل الأساسي (HTML)

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>أداة تحويل النص إلى كلام متعددة اللغات</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <h1>محول النص إلى كلام</h1>
        
        <div class="language-selection">
            <label for="language">اختر اللغة:</label>
            <select id="language">
                <option value="ar-SA">العربية (السعودية)</option>
                <option value="en-US">الإنجليزية (أمريكية)</option>
                <option value="fr-FR">الفرنسية</option>
                <option value="es-ES">الإسبانية</option>
                <option value="de-DE">الألمانية</option>
            </select>
        </div>
        
        <div class="voice-selection">
            <label for="voice">اختر الصوت:</label>
            <select id="voice"></select>
        </div>
        
        <div class="controls">
            <label for="rate">السرعة:</label>
            <input type="range" id="rate" min="0.5" max="2" step="0.1" value="1">
            <span id="rate-value">1</span>
            
            <label for="pitch">النبرة:</label>
            <input type="range" id="pitch" min="0.5" max="2" step="0.1" value="1">
            <span id="pitch-value">1</span>
        </div>
        
        <textarea id="text-to-speak" placeholder="أدخل النص هنا..."></textarea>
        
        <div class="buttons">
            <button id="speak-btn">تشغيل</button>
            <button id="pause-btn">إيقاف مؤقت</button>
            <button id="resume-btn">استئناف</button>
            <button id="stop-btn">إيقاف</button>
        </div>
        
        <div class="download-section">
            <button id="download-btn">تحميل كملف صوتي</button>
        </div>
    </div>
    
    <script src="script.js"></script>
</body>
</html>

الخطوة 2: التنسيق باستخدام CSS

/* styles.css */
body {
    font-family: Arial, sans-serif;
    line-height: 1.6;
    margin: 0;
    padding: 20px;
    background-color: #f5f5f5;
}

.container {
    max-width: 800px;
    margin: 0 auto;
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

h1 {
    text-align: center;
    color: #333;
}

.language-selection, .voice-selection, .controls {
    margin-bottom: 15px;
}

label {
    display: inline-block;
    margin-right: 10px;
    width: 100px;
}

select, input[type="range"] {
    vertical-align: middle;
}

textarea {
    width: 100%;
    height: 150px;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    resize: vertical;
    margin-bottom: 15px;
    font-size: 16px;
}

.buttons {
    display: flex;
    gap: 10px;
    margin-bottom: 15px;
}

button {
    padding: 10px 15px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
    flex: 1;
}

button:hover {
    background-color: #45a049;
}

#stop-btn {
    background-color: #f44336;
}

#stop-btn:hover {
    background-color: #d32f2f;
}

#pause-btn {
    background-color: #ff9800;
}

#pause-btn:hover {
    background-color: #e68a00;
}

.download-section {
    text-align: center;
}

#download-btn {
    background-color: #2196F3;
}

#download-btn:hover {
    background-color: #0b7dda;
}

الخطوة 3: إضافة الوظائف باستخدام JavaScript

// script.js
document.addEventListener('DOMContentLoaded', function() {
    const textInput = document.getElementById('text-to-speak');
    const languageSelect = document.getElementById('language');
    const voiceSelect = document.getElementById('voice');
    const rateInput = document.getElementById('rate');
    const pitchInput = document.getElementById('pitch');
    const rateValue = document.getElementById('rate-value');
    const pitchValue = document.getElementById('pitch-value');
    const speakBtn = document.getElementById('speak-btn');
    const pauseBtn = document.getElementById('pause-btn');
    const resumeBtn = document.getElementById('resume-btn');
    const stopBtn = document.getElementById('stop-btn');
    const downloadBtn = document.getElementById('download-btn');
    
    let speechSynthesis = window.speechSynthesis;
    let speechUtterance = null;
    let voices = [];
    
    // تحديث قيم السرعة والنبرة
    rateInput.addEventListener('input', () => {
        rateValue.textContent = rateInput.value;
    });
    
    pitchInput.addEventListener('input', () => {
        pitchValue.textContent = pitchInput.value;
    });
    
    // جلب الأصوات المتاحة
    function loadVoices() {
        voices = speechSynthesis.getVoices();
        voiceSelect.innerHTML = '';
        
        voices.forEach(voice => {
            const option = document.createElement('option');
            option.textContent = `${voice.name} (${voice.lang})`;
            option.setAttribute('data-lang', voice.lang);
            option.setAttribute('data-name', voice.name);
            voiceSelect.appendChild(option);
        });
    }
    
    // عند تغيير اللغة، نحدد الأصوات المتاحة لهذه اللغة
    languageSelect.addEventListener('change', function() {
        const selectedLang = this.value;
        voices = speechSynthesis.getVoices();
        
        voiceSelect.innerHTML = '';
        
        voices.forEach(voice => {
            if (voice.lang === selectedLang || voice.lang.startsWith(selectedLang.split('-')[0])) {
                const option = document.createElement('option');
                option.textContent = `${voice.name} (${voice.lang})`;
                option.setAttribute('data-lang', voice.lang);
                option.setAttribute('data-name', voice.name);
                voiceSelect.appendChild(option);
            }
        });
    });
    
    // تشغيل النص
    speakBtn.addEventListener('click', function() {
        if (textInput.value.trim() === '') {
            alert('الرجاء إدخال نص لتحويله إلى كلام');
            return;
        }
        
        stopSpeaking(); // إيقاف أي كلام جاري
        
        speechUtterance = new SpeechSynthesisUtterance(textInput.value);
        
        const selectedVoice = voiceSelect.selectedOptions[0].getAttribute('data-name');
        if (selectedVoice) {
            speechUtterance.voice = voices.find(voice => voice.name === selectedVoice);
        }
        
        speechUtterance.lang = languageSelect.value;
        speechUtterance.rate = parseFloat(rateInput.value);
        speechUtterance.pitch = parseFloat(pitchInput.value);
        
        speechSynthesis.speak(speechUtterance);
    });
    
    // إيقاف مؤقت
    pauseBtn.addEventListener('click', function() {
        speechSynthesis.pause();
    });
    
    // استئناف
    resumeBtn.addEventListener('click', function() {
        speechSynthesis.resume();
    });
    
    // إيقاف
    stopBtn.addEventListener('click', stopSpeaking);
    
    function stopSpeaking() {
        speechSynthesis.cancel();
    }
    
    // تحميل الملف الصوتي (يتطلب API إضافية للتحويل إلى ملف)
    downloadBtn.addEventListener('click', function() {
        alert('هذه الميزة تتطلب استخدام API خاص مثل Google Cloud Text-to-Speech أو Amazon Polly لتحويل النص إلى ملف صوتي. يمكنك تنفيذ هذا الجزء باستخدام AJAX للاتصال بالخادم.');
    });
    
    // تهيئة الأصوات عند تحميل الصفحة
    speechSynthesis.onvoiceschanged = loadVoices;
    loadVoices(); // تحميل الأصوات مباشرة إذا كانت متاحة
    
    // إذا لم يتم تحميل الأصوات، نعيد المحاولة بعد فترة
    if (speechSynthesis.getVoices().length === 0) {
        speechSynthesis.addEventListener('voiceschanged', loadVoices);
    }
});

الخطوة 4: استخدام API متقدمة (اختياري)

إذا كنت تريد جودة صوت أفضل أو تحميل الملفات الصوتية، يمكنك استخدام واجهات برمجة التطبيقات المدفوعة مثل:

  1. Google Cloud Text-to-Speech API
  2. Amazon Polly
  3. IBM Watson Text to Speech

مثال باستخدام Google Text-to-Speech API:

async function convertTextToSpeechWithAPI(text, language) {
    try {
        const response = await fetch('https://texttospeech.googleapis.com/v1/text:synthesize', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer YOUR_API_KEY'
            },
            body: JSON.stringify({
                input: { text: text },
                voice: { languageCode: language },
                audioConfig: { audioEncoding: 'MP3' }
            })
        });
        
        const data = await response.json();
        return data.audioContent;
    } catch (error) {
        console.error('Error calling Google TTS API:', error);
        return null;
    }
}

الخطوة 5: دمج الأداة مع موقعك أو مدونتك

  1. أنشئ مجلدًا جديدًا في موقعك وأضف ملفات HTML وCSS وJavaScript.
  2. يمكنك تضمين الأداة في أي صفحة باستخدام iframe أو تضمينها مباشرة.
  3. إذا كنت تستخدم نظام إدارة محتوى مثل WordPress، يمكنك إنشاء صفحة مخصصة وإضافة الكود عبر ميزة "HTML مخصص".

نصائح لتحسين الأداة

  1. إضافة المزيد من اللغات: يمكنك إضافة المزيد من خيارات اللغات حسب احتياجات جمهورك.
  2. حفظ التفضيلات: استخدم localStorage لحفظ تفضيلات المستخدم (اللغة، الصوت، السرعة، النبرة).
  3. واجهة مستخدم أفضل: أضف مؤشر تحميل أثناء انتظار تحويل النص إلى كلام.
  4. دعم المزيد من الميزات: مثل اختيار نوع الصوت (ذكر/أنثى) أو لهجة معينة.

الخاتمة

في هذا المقال، تعلمنا كيفية إنشاء أداة تحويل النص إلى كلام متعددة اللغات باستخدام تقنيات الويب الأساسية وWeb Speech API. 

و هذه الأداة يمكن أن تكون إضافة قيمة لموقعك أو مدونتك، خاصة للزوار الذين يفضلون الاستماع إلى المحتوى أو الذين يعانون من صعوبات في القراءة.

تذكر أن Web Speech API قد يكون دعمه للغات محدودًا حسب المتصفح، وللحصول على جودة صوت أفضل ودعم لغات أوسع، قد تحتاج إلى استخدام واجهات برمجة التطبيقات المدفوعة مثل Google Cloud Text-to-Speech أو Amazon Polly.

تجربة الأداة

1 1
أحدث أقدم

نموذج الاتصال