NeteaseCloudMusicApi

repository·main·Indexed 41 days ago

https://github.com/2061360308/neteasecloudmusic_pythonsdk

A unified API for music platforms like NetEase Cloud Music and Kugou. It provides endpoints for user authentication (QR code, email, mobile), playlist management, social activity tracking, and artist exploration. Supports deployment via Docker, Vercel, and Tencent Cloud Serverless, and can be integrated as a Node.js or TypeScript module.

Tokens
45.1K
Snippets
223
Records
257
Agent score
52%

What's inside NeteaseCloudMusicApi

  1. Overview of MusicLibrary Language Bindings

    main

    MusicLibrary is a multi-language binding project for the MusicLibrary core. It provides a unified interface for music platforms like NetEase Cloud Music and Kugou Music using a unique architecture:

    1. Logic Layer: API logic is implemented in JavaScript/Node.js.
    2. Engine Layer: Logic is bundled via Webpack and executed by the QuickJS engine.
    3. Interface Layer: The engine is encapsulated into C interfaces.
    4. Binding Layer: These C interfaces are distributed as bindings for languages like Python and Dart.

    This architecture ensures high performance, low memory usage, and a lightweight footprint (approximately 2MB) while providing access to over 100+ APIs covering login, search, playback, and comments.

  2. Available features for KuGouMusic and NeteaseCloudMusic

    main

    The SDK provides a wide range of interfaces for both KuGouMusic and NeteaseCloudMusic. Key categories of functionality include:

    • Authentication: Login, refresh login, sending verification codes, and QR code login.
    • User Data: Fetching user info, VIP status, playlists, favorites, following lists, and listening history.
    • Music Discovery: Searching (including suggestions and lyrics search), hot search lists, daily recommendations, and genre/style browsing.
    • Content Details: Fetching song details, album info, lyrics, comments, and MV/video information.
    • Playlist Management: Creating, deleting, and editing playlists, as well as adding/removing songs.
    • Social & Interaction: Following artists, sending private messages, liking comments, and viewing user dynamics.
    • Radio & Podcasts: Radio station info, program details, and podcast searching/uploading.
    • Cloud Storage & VIP: Cloud drive (Yunpan) operations, VIP task management, and Yunbei (cloud coin) balance/tasks.

    Note: As this project is intended for learning purposes, not all listed interfaces are guaranteed to be fully tested. Users are encouraged to report errors via issues or Pull Requests.

    See the full feature table in the repository README for the complete list of 316+ specific endpoints.

  3. Thread safety warning for API objects

    main

    Important: API objects like KuGouMusicApi and NeteaseCloudMusicApi are not thread-safe and cannot be shared across threads. If you need to perform concurrent requests, you must create a unique instance of the API class for every thread.

    from threading import Thread
    from MusicLibrary.neteaseCloudMusicApi import NeteaseCloudMusicApi
    
    # CORRECT: Create a new instance inside the worker thread
    def worker():
        api = NeteaseCloudMusicApi()
        return api.playlist_mylike()
    
    Thread(target=worker).start()
  4. Understand the structure of LRC and YRC lyrics

    main

    The API provides two types of lyric formats:

    1. YRC (JSON Metadata): When applicable, the lyric field may contain JSON song metadata. This metadata includes:

      • t: Timestamp for when the data should be displayed (milliseconds).
      • c: A list of metadata objects.
      • tx: The text content.
      • li: URL for the artist/singer's avatar.
      • or: Internal Netease Cloud Music app path (e.g., to open an artist's home page).
    2. 逐字歌词 (Word-by-word lyrics): Uses a specific bracketed format [start_time, end_time](start_time, duration, unknown)text.

      • The first pair [16210,3460] represents the lyric line's start time and total duration (milliseconds).
      • The second set (16210,670,0) represents the word-level start time (ms), duration (centiseconds/0.01s), and an unknown value.
    /* Example YRC JSON Metadata */
    {"t":0,"c":[{"tx":"作曲: "},{"tx":"柳重言","li":"http://...","or":"orpheus://..."}]}
    
    /* Example Word-by-word lyrics */
    [16210,3460](16210,670,0)还(16880,410,0)没...
  5. Understand the Response object

    main

    All API requests return a unified Response object that automatically parses JSON response strings.

    Attributes:

    • status (int): HTTP status code. 200 indicates success. If parsing fails, it defaults to 500.
    • headers (dict): Response header information. Defaults to an empty dictionary on failure.
    • body / data (dict): The parsed response body. body and data are equivalent. Defaults to an empty dictionary on failure.
    • cookies (str): The Set-Cookie value extracted from headers (useful for login interfaces).

    Note: The Response object will not raise exceptions on parsing failure; it will instead return default values (status=500, headers={}, body={}).

    from MusicLibrary.neteaseCloudMusicApi import NeteaseCloudMusicApi
    
    ncm = NeteaseCloudMusicApi()
    response = ncm.playlist_mylike()
    
    # Check status
    if response.status == 200:
        # Access data via .body or .data
        songs = response.body.get('playlist', {}).get('tracks', [])
    
    # Access cookies
    cookies = response.cookies
  6. Quickstart with NeteaseCloudMusicApi

    main

    You can interact with Netease Cloud Music using the NeteaseCloudMusicApi class. When initializing the API, you must provide the libraryDir parameter, which points to the directory containing the precompiled native dynamic libraries (e.g., ./libs/lib).

    Note: On Windows, if the native libraries are not in your system's global PATH, you must add the library directory to your current session's PATH before running the application.

    import 'package:musiclibrary/music_library.dart';
    
    final ncm = NeteaseCloudMusicApi(libraryDir: './libs/lib');
    final response = await ncm.playlistMyLike();
    
    if (response.status == 200) {
      final songs = response.body['playlist']['tracks'];
    }
    print(response);
  7. Important usage notes for NeteaseCloudMusicApi

    main

    Before using the API, be aware of the following operational constraints and troubleshooting steps:

    • Caching: The API implements a 2-minute cache. Identical URLs within 2 minutes will only trigger one request to Netease servers. To bypass cache for a specific request, append a unique timestamp parameter to the URL (e.g., /simi/playlist?id=347230&timestamp=1503019930000).
    • Cross-Origin Requests (CORS): If making cross-origin requests, you must include xhrFields: { withCredentials: true } in your request (e.g., using Axios or jQuery) to ensure cookies are sent. Failure to do so may result in 301 errors.
    • 301 Errors: These typically indicate an attempt to access a protected endpoint without being logged in. If you are logged in but still see 301, it is likely due to the 2-minute cache; wait 2 minutes or restart the service.
    • Rate Limiting: Frequent calls to the login interface may trigger 503 errors or IP frequency limits. Consider using an IP proxy pool if high-frequency calling is required.
    • International Server Restrictions: If using a server outside mainland China, you may face restrictions. A workaround is to add a domestic IP to the headers in util.js (e.g., 'X-Real-IP': '211.161.244.70').
  8. Run NeteaseCloudMusicApi

    main

    Start the server using Node.js. By default, the server runs on port 3000. You can change the port by setting the PORT environment variable.

    # Default port 3000
    $ node app.js
    
    # Mac/Linux: Custom port
    $ PORT=4000 node app.js
    
    # Windows (Git-Bash/Cmder): Custom port
    $ set PORT=4000 && node app.js
  9. Deploy to Vercel

    main

    The project includes Vercel configuration files for easy deployment.

    Important Note: When accessing interfaces deployed on Vercel, you must append a realIP parameter to your requests (e.g., /song/url?id=191254&realIP=116.25.146.177). If the service is inaccessible, try binding a domain that has been registered in China.

    Steps:

    1. Fork the repository.
    2. In the Vercel dashboard, click New Project and Import Git Repository.
    3. Select your forked repository.
    4. Under Framework Preset, select Other.
    5. Click Deploy.