Electron Desktop App Development · บทเรียน

การจับภาพหน้าจอและสื่อ

สำรวจวิธีเข้าถึงความสามารถในการจับภาพหน้าจอและอุปกรณ์สื่อ พร้อมผสานรวมสิ่งเหล่านี้เข้ากับแอปพลิเคชันเดสก์ท็อป Electron

บทเรียน 3 จาก 411 ขั้นตอน

การจับภาพหน้าจอและสื่อ เป็นบทเรียน Electron Desktop App Development ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Electron Desktop App Development และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Electron Desktop App Development มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Accessing Camera & Screen

Electron lets your desktop app use native features like cameras, microphones, and even capture the screen. This opens up possibilities for video calls, screen recording, and more!

We'll explore how to list available devices, display live camera feeds, and capture your desktop or specific windows.

Discovering Your Devices

Before using a camera or microphone, you can discover what's available on the user's system. The navigator.mediaDevices.enumerateDevices() method provides a list of all connected media input and output devices.

Run this code to see your devices. You might need to grant permission to access devices.

const { app, BrowserWindow } = require('electron');

function createWindow() {
  const win = new BrowserWindow({
    width: 600,
    height: 450,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false // Simplifies example for A1. Use preload scripts for security in real apps.
    }
  });

  const htmlContent = `
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Media Devices</title>
    </head>
    <body>
        <h1>Available Media Devices</h1>
        <ul id="device-list"></ul>

        <script>
            async function getMediaDevices() {
                try {
                    const devices = await navigator.mediaDevices.enumerateDevices();
                    const list = document.getElementById('device-list');
                    if (devices.length === 0) {
                        list.innerHTML = '<li>No media devices found or permission denied.</li>';
                        return;
                    }
                    devices.forEach(device => {
                        const li = document.createElement('li');
                        li.textContent = `Kind: ${device.kind}, Label: ${device.label || 'Unknown'}`; 
                        list.appendChild(li);
                    });
                } catch (err) {
                    console.error('Error listing devices:', err);
                    document.getElementById('device-list').innerHTML = `<li>Error: ${err.message}</li>`;
                }
            }
            getMediaDevices();
        </script>
    </body>
    </html>
  `;
  win.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(htmlContent)}`);
}

app.whenReady().then(createWindow);
app.on('window-all-closed', () => app.quit());
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

Displaying Camera Stream

To display a live camera feed, we use navigator.mediaDevices.getUserMedia(). This method requests access to a media input device (like a camera) and, if granted, provides a MediaStream.

This stream can then be displayed in a <video> element. Try running this example:

const { app, BrowserWindow } = require('electron');

function createWindow() {
  const win = new BrowserWindow({
    width: 600,
    height: 450,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false // Simplifies example for A1. Use preload scripts for security in real apps.
    }
  });

  const htmlContent = `
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Camera Stream</title>
    </head>
    <body>
        <h1>My Camera Feed</h1>
        <video id="camera-feed" autoplay style="width:100%; height:auto;"></video>
        <p id="status"></p>

        <script>
            async function startCamera() {
                const video = document.getElementById('camera-feed');
                const status = document.getElementById('status');
                try {
                    const stream = await navigator.mediaDevices.getUserMedia({
                        video: true // Request video access
                    });
                    video.srcObject = stream;
                    status.textContent = 'Camera feed active.';
                } catch (err) {
                    console.error('Error accessing camera:', err);
                    status.textContent = `Error: ${err.message}. Please grant camera permission.`;
                }
            }
            startCamera();
        </script>
    </body>
    </html>
  `;
  win.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(htmlContent)}`);
}

app.whenReady().then(createWindow);
app.on('window-all-closed', () => app.quit());
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

User Permissions & Errors

Accessing media devices like cameras and microphones requires explicit user permission. When getUserMedia() is called, the operating system will typically prompt the user for consent.

  • Your application should always be ready to handle cases where the user grants or denies permission.
  • Catching errors from getUserMedia() (e.g., NotAllowedError) helps you inform the user about permission issues.

Understanding DesktopCapturer

Electron provides the desktopCapturer module, a powerful tool that allows your app to capture video and audio from the entire screen, specific windows, or individual displays.

This is essential for building features like screen sharing, screen recording, or even taking screenshots of other applications running on the user's desktop.

Getting Screen Sources

To capture a screen or window, you first need to get a list of available sources. desktopCapturer.getSources() provides these, including their IDs, names, and even thumbnails.

This method is available in the renderer process (but usually exposed via a preload script for security). For simplicity in this lesson, we'll access it directly.

const { app, BrowserWindow } = require('electron');

function createWindow() {
  const win = new BrowserWindow({
    width: 600,
    height: 450,
    webPreferences: {
      nodeIntegration: true, // Required for desktopCapturer
      contextIsolation: false // Simplifies example for A1. Use preload scripts for security in real apps.
    }
  });

  const htmlContent = `
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Screen Sources</title>
    </head>
    <body>
        <h1>Available Screen Sources</h1>
        <ul id="source-list"></ul>

        <script>
            const { desktopCapturer } = require('electron'); // Access desktopCapturer

            async function getScreenSources() {
                const list = document.getElementById('source-list');
                try {
                    const sources = await desktopCapturer.getSources({
                        types: ['window', 'screen']
                    });

                    if (sources.length === 0) {
                        list.innerHTML = '<li>No screen or window sources found.</li>';
                        return;
                    }

                    sources.forEach(source => {
                        const li = document.createElement('li');
                        li.textContent = `ID: ${source.id}, Name: ${source.name}`; 
                        if (source.thumbnail) {
                            const img = document.createElement('img');
                            img.src = source.thumbnail.toDataURL();
                            img.style.maxWidth = '100px';
                            img.style.marginLeft = '10px';
                            li.appendChild(img);
                        }
                        list.appendChild(li);
                    });
                } catch (err) {
                    console.error('Error getting sources:', err);
                    list.innerHTML = `<li>Error: ${err.message}</li>`;
                }
            }
            getScreenSources();
        </script>
    </body>
    </html>
  `;
  win.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(htmlContent)}`);
}

app.whenReady().then(createWindow);
app.on('window-all-closed', () => app.quit());
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

Displaying a Screen Stream

Once you have a source ID (e.g., from a specific display or window), you can use navigator.mediaDevices.getUserMedia() again. This time, you pass a chromeMediaSource constraint with the desktopCapturer source ID.

This will capture the chosen screen/window and display it in a <video> element, similar to a camera feed.

const { app, BrowserWindow } = require('electron');

function createWindow() {
  const win = new BrowserWindow({
    width: 600,
    height: 450,
    webPreferences: {
      nodeIntegration: true, // Required for desktopCapturer
      contextIsolation: false // Simplifies example for A1. Use preload scripts for security in real apps.
    }
  });

  const htmlContent = `
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Screen Capture</title>
    </head>
    <body>
        <h1>Screen Capture Demo</h1>
        <button id="start-capture">Start Screen Capture</button>
        <video id="screen-feed" autoplay style="width:100%; height:auto;"></video>
        <p id="status"></p>

        <script>
            const { desktopCapturer } = require('electron');

            document.getElementById('start-capture').addEventListener('click', async () => {
                const video = document.getElementById('screen-feed');
                const status = document.getElementById('status');
                status.textContent = 'Searching for sources...';

                try {
                    const sources = await desktopCapturer.getSources({
                        types: ['screen'], // Only screens for simplicity
                        thumbnailSize: { width: 1, height: 1 } // No large thumbnails needed
                    });

                    if (sources.length === 0) {
                        status.textContent = 'No screen sources found.';
                        return;
                    }

                    // Take the first screen found
                    const screenSource = sources[0]; 
                    status.textContent = `Capturing: ${screenSource.name}`;

                    const stream = await navigator.mediaDevices.getUserMedia({
                        audio: false, // Can be true for audio
                        video: {
                            mandatory: {
                                chromeMediaSource: 'desktop',
                                chromeMediaSourceId: screenSource.id,
                                minWidth: 1280, minHeight: 720,
                                maxWidth: 1920, maxHeight: 1080
                            }
                        }
                    });
                    video.srcObject = stream;
                    status.textContent = 'Screen capture active.';

                } catch (err) {
                    console.error('Error capturing screen:', err);
                    status.textContent = `Error: ${err.message}.`;
                }
            });
        </script>
    </body>
    </html>
  `;
  win.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(htmlContent)}`);
}

app.whenReady().then(createWindow);
app.on('window-all-closed', () => app.quit());
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

Basic Media Recording

After getting a MediaStream (from a camera or screen), you can record it using the browser's MediaRecorder API. This lets you save the stream as a video or audio file.

The MediaRecorder takes the stream and collects data chunks, which can then be combined into a Blob (e.g., a video file).

const { app, BrowserWindow } = require('electron');

function createWindow() {
  const win = new BrowserWindow({
    width: 600,
    height: 450,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false // Simplifies example for A1. Use preload scripts for security in real apps.
    }
  });

  const htmlContent = `
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Media Recorder</title>
    </head>
    <body>
        <h1>Simple Recorder</h1>
        <button id="start-cam">Start Camera</button>
        <button id="start-rec" disabled>Record</button>
        <button id="stop-rec" disabled>Stop</button>
        <video id="live-feed" autoplay muted style="width:100%; height:auto;"></video>
        <a id="download-link" style="display:none;">Download Recording</a>
        <p id="status"></p>

        <script>
            const startCamBtn = document.getElementById('start-cam');
            const startRecBtn = document.getElementById('start-rec');
            const stopRecBtn = document.getElementById('stop-rec');
            const downloadLink = document.getElementById('download-link');
            const liveFeed = document.getElementById('live-feed');
            const status = document.getElementById('status');

            let mediaRecorder;
            let recordedChunks = [];
            let currentStream;

            startCamBtn.addEventListener('click', async () => {
                try {
                    currentStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
                    liveFeed.srcObject = currentStream;
                    startRecBtn.disabled = false;
                    startCamBtn.disabled = true;
                    status.textContent = 'Camera ready. Click Record.';
                } catch (err) {
                    status.textContent = `Error: ${err.message}`;
                    console.error('Error starting camera:', err);
                }
            });

            startRecBtn.addEventListener('click', () => {
                recordedChunks = [];
                mediaRecorder = new MediaRecorder(currentStream);
                mediaRecorder.ondataavailable = event => {
                    if (event.data.size > 0) {
                        recordedChunks.push(event.data);
                    }
                };
                mediaRecorder.onstop = () => {
                    const blob = new Blob(recordedChunks, { type: 'video/webm' });
                    const url = URL.createObjectURL(blob);
                    downloadLink.href = url;
                    downloadLink.download = 'electron-recording.webm';
                    downloadLink.style.display = 'block';
                    status.textContent = 'Recording stopped. Download available.';
                };
                mediaRecorder.start();
                startRecBtn.disabled = true;
                stopRecBtn.disabled = false;
                status.textContent = 'Recording...';
            });

            stopRecBtn.addEventListener('click', () => {
                mediaRecorder.stop();
                startRecBtn.disabled = false;
                stopRecBtn.disabled = true;
            });
        </script>
    </body>
    </html>
  `;
  win.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(htmlContent)}`);
}

app.whenReady().then(createWindow);
app.on('window-all-closed', () => app.quit());
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

Security Best Practices

When working with native media, always prioritize security. Granting access to cameras, microphones, or screen capture can be sensitive.

  • Request Permissions Wisely: Only ask for permissions when absolutely necessary for your app's functionality.
  • Inform Users: Clearly explain why your app needs access to these native features.
  • Context Isolation & Preload Scripts: For real-world applications, use contextIsolation: true and expose desktopCapturer securely via a preload script. This prevents malicious scripts in the renderer from accessing Node.js APIs directly.

Quick Check: Native Media

Which of the following statements are true regarding accessing native media and screen capture in Electron?

Recap: Native Media

Great job! In this lesson, we explored how Electron applications can interact with native media features:

  • We learned to use navigator.mediaDevices.enumerateDevices() to list available cameras and microphones.
  • We accessed live camera feeds with navigator.mediaDevices.getUserMedia().
  • We discovered the desktopCapturer module for listing and capturing screen or window content.
  • We briefly touched upon using MediaRecorder to save captured media streams.
  • Finally, we highlighted the importance of user permissions and security best practices when handling sensitive native features.

These tools empower you to build rich, interactive desktop applications with powerful media capabilities!

เริ่มต้นได้ฟรี

เรียนรู้ JavaScript ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
12
บทเรียน
47

คำถามที่พบบ่อย

บทเรียน “การจับภาพหน้าจอและสื่อ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การจับภาพหน้าจอและสื่อ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Electron Desktop App Development ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Electron Desktop App Development มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การจับภาพหน้าจอและสื่อ”

สำรวจวิธีเข้าถึงความสามารถในการจับภาพหน้าจอและอุปกรณ์สื่อ พร้อมผสานรวมสิ่งเหล่านี้เข้ากับแอปพลิเคชันเดสก์ท็อป Electron คุณปฏิบัติ Electron Desktop App Development ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Electron Desktop App Development หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Electron Desktop App Development บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การจับภาพหน้าจอและสื่อ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Electron Desktop App Development นี้ได้ไหม

ได้ บทเรียน Electron Desktop App Development ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การทำงานกับโมดูลเนทีฟ
  2. แอปพลิเคชันถาดระบบและป้ายแจ้งเตือน
  3. การจับภาพหน้าจอและสื่อ
  4. การตรวจสอบพลังงานและฮาร์ดแวร์
← กลับไปที่ Electron Desktop App Development