Y2Mp3

repository·master·Indexed 41 days ago

https://github.com/moshfeu/y2mp3

A desktop application built with Electron for downloading YouTube videos and audio in multiple formats, including mp3, wav, flac, m4a, wma, ogg, acc, mp4, mpg, and wmv. It supports downloading individual videos or playlists (up to 100 clips) and includes a built-in FFmpeg installer for audio encoding.

Tokens
6.2K
Snippets
28
Records
34
Agent score
100%

What's inside Y2Mp3

  1. What is Y2Mp3?

    master

    Y2Mp3 is a desktop application used to download YouTube videos in various video and audio formats. It supports downloading individual videos or entire playlists.

    Supported Video Formats:

    • mp4
    • mpg
    • wmv

    Supported Audio Formats:

    • mp3
    • wav
    • flac
    • m4a
    • wma
    • ogg
    • acc

    Limitations:

    • When downloading a playlist, the app can only fetch the first 100 clips.
  2. Download Y2Mp3

    master

    The application is free, contains no ads, and is available for Windows, macOS, and Linux. You can find the latest binaries in the GitHub releases section.

    https://github.com/moshfeu/y2mp3/releases/latest
  3. Set up the Y2Mp3 development environment

    master

    To run the project locally for development, use either npm or yarn to install dependencies and start the application.

    # Using npm
    npm install
    npm start
    
    # Using yarn
    yarn
    yarn start
  4. Monitor download states with StateChangeAction

    master

    The onStateChanged callback receives StateChangeAction objects. Use the state property to determine the current phase of the download and the payload to access relevant data.

    Available States:

    • added: Payload is the videoId.
    • getting info: Payload is the videoId.
    • downloading: Payload contains videoId and progress (percentage, speed, etc.).
    • done: Payload contains videoId, thumbnail, videoTitle, artist, title, file, and youtubeUrl.
    • error: Payload contains a partial IVideoTask and the error object.
  5. Configure application settings via IConfig

    master

    The application's configuration is managed through the IConfig interface, implemented by the settingsManager singleton. Settings are persisted in localStorage.

    Key configuration properties include:

    • downloadsFolder: The file system path where downloads are saved. Updating this also updates the downloader output path.
    • audioQuality: The desired DownloadQuality (e.g., 'highest'). Updating this also updates the downloader quality.
    • downloadFormat: The target DownloadFormat (e.g., 'mp3'). Updating this also updates the downloader format.
    • playlistFolder: A boolean indicating if playlists should be handled in a specific folder.
    • autoPaste: A boolean determining if the URL is automatically pasted.
    • checkForUpdate: A boolean to enable/disable update checks.
    • albumArt: A boolean to enable/disable album art embedding.
    • notificationWhenDone: A boolean to enable/disable notifications upon download completion.
    import { settingsManager } from './services/settings';
    
    // Example: Updating settings
    settingsManager.downloadsFolder = '/path/to/downloads';
    settingsManager.audioQuality = 'highest';
    settingsManager.albumArt = true;
    
    // Example: Reading settings
    const currentFolder = settingsManager.downloadsFolder;
    const isAutoPasteEnabled = settingsManager.autoPaste;
  6. Configure YoutubeMp3DownloaderOptions

    master

    When instantiating YoutubeMp3Downloader, provide the following configuration options:

    KeyTypeDescription
    ffmpegPathstringAbsolute path to the ffmpeg executable.
    outputPathstringDirectory where downloaded files will be saved.
    youtubeVideoQualityDownloadQualityDesired quality (e.g., 'highest', 'lowest', or a specific number/string).
    filterDownloadFilterFilter options passed to @distube/ytdl-core (e.g., 'audioonly').
    formatDownloadFormatThe target file format (e.g., 'mp3', 'wav', 'm4a').
    progressTimeoutnumberTimeout for progress updates.
    outputOptionsstring[] (optional)Additional command-line arguments for ffmpeg.
  7. Fetch video entities from a URL

    master

    The fetchVideos function resolves a string (URL or search term) into an array of IVideoEntity objects.

    • If the input is a single YouTube video URL, it returns an array containing that one video.
    • If the input is a YouTube playlist URL, it scrapes the playlist and returns an array of all video entities within it.
    • If the input is not a valid YouTube URL, it returns an empty array.
    const videos = await fetchVideos('https://www.youtube.com/watch?v=...');
  8. Install FFmpeg using installFfmpeg

    master

    The installFfmpeg function downloads and installs the ffmpeg binary to the application's APPDATA_FOLDER. It accepts a tickerFn callback to report download progress. This is useful for ensuring the required media processing dependencies are present on the user's system.

    import { installFfmpeg } from './services/ffmpeg-installer';
    
    // Example usage with a progress ticker
    await installFfmpeg(({ progress }) => {
      console.log(`Download progress: ${progress * 100}%`);
    });
  9. Use the YoutubeMp3Downloader class

    master

    The YoutubeMp3Downloader class is the primary interface for managing YouTube to MP3 (or other audio/video formats) downloads. It manages a download queue, handles metadata extraction, and uses ffmpeg for encoding and album art embedding.

    To use it, instantiate the class with YoutubeMp3DownloaderOptions and call .download(videoId, onStateChanged) to add a task to the queue. You can monitor the lifecycle of a download via the onStateChanged callback.

    import { YoutubeMp3Downloader } from './services/youtube-mp3-downloader';
    
    const downloader = new YoutubeMp3Downloader({
      ffmpegPath: '/path/to/ffmpeg',
      outputPath: './downloads',
      youtubeVideoQuality: 'highest',
      filter: 'audioonly',
      format: 'mp3',
      progressTimeout: 1000,
      outputOptions: ['-id3v2_version', '4']
    });
    
    downloader.download('VIDEO_ID_HERE', (action) => {
      switch (action.state) {
        case 'added':
          console.log('Task added:', action.payload);
          break;
        case 'getting info':
          console.log('Fetching metadata...');
          break;
        case 'downloading':
          console.log(`Progress: ${action.payload.progress.percentage}%`);
          break;
        case 'done':
          console.log('Download complete!', action.payload);
          break;
        case 'error':
          console.error('Download failed:', action.error);
          break;
      }
    });
  10. Manually hide UI messages

    master

    The hideMessage function allows you to programmatically hide the currently visible message. You can pass an optional timeout in milliseconds. If a timeout is provided, the message will be hidden after that duration. It returns a Promise that resolves once the message is hidden.

    import { hideMessage } from './services/modalsAndAlerts';
    
    // Hide the current message immediately
    hideMessage();
    
    // Hide the current message after 5 seconds
    hideMessage(5000);
  11. Check FFmpeg availability and configuration

    master

    The API provides utilities to manage the FFmpeg dependency required for audio encoding:

    • isFfmpegInPath(): Returns a boolean indicating if the ffmpeg command is available in the system's PATH.
    • setFfmpegPath(): Configures the underlying fluent-ffmpeg instance to use the path returned by the internal ffmpegPath() utility.
    if (isFfmpegInPath()) {
      setFfmpegPath();
    } else {
      console.error('FFmpeg is not installed');
    }