const express = require('express'); const ytdl = require('@distube/ytdl-core'); const app = express(); const PORT = 3000; // الـ Endpoint الخاص بتحميل الصوت app.get('/download-audio', async (req, res) => { const videoUrl = req.query.url; // التأكد من أن المستخدم أرسل رابط الفيديو if (!videoUrl) { return res.status(400).send('برجاء إرسال رابط فيديو يوتيوب صحيح. مثال: ?url=https://youtube.com/...'); } try { // 1. جلب معلومات الفيديو (مثل الاسم) لتسمية الملف عند التحميل const info = await ytdl.getInfo(videoUrl); // تنظيف اسم الفيديو من الرموز الغريبة عشان ما يحصلش مشكلة في التحميل const videoTitle = info.videoDetails.title.replace(/[^\w\s]/gi, ''); // 2. إعداد الـ Headers لتجبر المتصفح على تحميل الملف بدل تشغيله res.setHeader('Content-Disposition', `attachment; filename="${videoTitle}.mp3"`); res.setHeader('Content-Type', 'audio/mpeg'); // 3. سحب الصوت فقط وتمريره مباشرة للرد (Stream) ytdl(videoUrl, { filter: 'audioonly', // سحب الصوت فقط بدون الفيديو quality: 'highestaudio' // الحصول على أعلى جودة صوت متاحة }).pipe(res); } catch (error) { console.error('حدث خطأ:', error.message); res.status(500).send('فشل تشغيل الطلب. تأكد من أن الرابط صحيح أو جرب لاحقاً.'); } }); // تشغيل السيرفر app.listen(PORT, () => { console.log(`السيرفر يعمل الآن على: http://localhost:${PORT}`); });