File size: 1,839 Bytes
d9c9159
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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}`);
});