ruby-mp3info

repository·master·Indexed 42 days ago

https://github.com/moumar/ruby-mp3info

A pure Ruby library for reading low-level MP3 information such as bitrate, length, and samplerate, and manipulating ID3v1 and ID3v2 tags. It provides a universal tag interface for common metadata like title, artist, and album, supports ID3v2.3 writing with UTF-16 encoding, and allows for the extraction and addition of album art (APIC tags).

Tokens
3.1K
Snippets
13
Records
16
Agent score
53%

What's inside ruby-mp3info

  1. Read and display MP3 information and tags

    master

    Use Mp3Info.open to access an MP3 file. When used with a block, the file is automatically closed at the end of the block, which triggers the writing of any modified tags.

    require "mp3info"
    
    Mp3Info.open("myfile.mp3") do |mp3info|
      puts mp3info
    end
  2. Use the ID3v2 class to manage ID3v2 tags

    master

    The ID3v2 class is used to decode and manipulate ID3v2 tags from files (e.g., .mp3, .ape). It behaves like a Hash, where keys are 3 or 4-character uppercase strings representing tag names (e.g., TIT2 for title, TPE1 for lead performer) and values are the tag data.

    Key behaviors:

    • Version Support: It can read ID3v2.2, v2.3, and v2.4 tags, but always writes tags in version 2.3 format.
    • Tag Mapping: It automatically translates ID3v2.2 tags to their ID3v2.3 equivalents (e.g., TAL becomes TALB).
    • Special Keys: It provides convenience keys disc_number and disc_total which mirror the TPOS attribute.
    • Encoding: It handles Unicode translation for text-based tags.
    # Example of how ID3v2 behaves like a hash
    # (Assuming an instance 'id3' has been initialized and parsed)
    
    title = id3["TIT2"]
    artist = id3["TPE1"]
    disc_num = id3["disc_number"]
  3. Read and write MP3 tags (ID3v1 and ID3v2)

    master

    The library provides a "universal" tag interface via the #tag attribute. This attribute maps common keys (like :title, :artist, :album, :year, :tracknum, :comments, :genre_s) to the appropriate ID3v1 or ID3v2 tags.

    Tag Priority and Writing

    • Reading: When reading, if ID3v2 tags are present, they take priority over ID3v1 tags. The #tag attribute is populated by merging these, with v2 values overriding v1.
    • Writing: When you modify the #tag attribute and call #close (or finish the #open block), the library writes the changes back to the file.
    • Priority: The #tag attribute has priority over both @tag1 and @tag2 when writing. If you modify #tag, those changes will be written to both tag versions during #close.

    Specific Tag Access

    • #tag1: Access or modify the ID3v1 tag as a Hash.
    • #tag2: Access or modify the ID3v2 tag as an ID3v2 object.
    • #tag: The universal mapping for both versions.
    Mp3Info.open("song.mp3") do |info|
      # Modify using the universal tag
      info.tag[:artist] = "New Artist"
      info.tag[:title] = "New Title"
    end # Changes are written to disk here
  4. Initialize and use Mp3Info

    master

    To read MP3 metadata and audio properties, use the Mp3Info.open method. This is the recommended way to instantiate the object as it ensures the file is properly closed after processing. You can pass a filename or an IO object (like StringIO).

    By default, the library parses both the MP3 audio headers and the ID3 tags. You can disable these via options:

    • :parse_mp3 => false: Disables audio property extraction (bitrate, samplerate, etc.).
    • :parse_tags => false: Disables ID3 tag reading/writing.
    • :parse_tags also accepts an options hash passed to the underlying ID3v2 parser.
    require 'mp3info'
    
    # Recommended: use the block version to ensure the file is closed
    Mp3Info.open("path/to/song.mp3") do |info|
      puts "Bitrate: #{info.bitrate} kbps"
      puts "Length: #{info.length} seconds"
      puts "Artist: #{info.tag[:artist]}"
    end
  5. Access and manipulate ID3v2 tags via Mp3Info#tag2

    master

    For specific ID3v2 frames, use the tag2 attribute. You can access four-letter v2 tags using method calls or string keys.

    Key behaviors:

    • Access via method: mp3.tag2.TIT2
    • Access via string key: mp3.tag2["TIT2"]
    • COMM (Comments): The COMM tag can be configured using the options hash. For example, to set a language: mp3.tag2.options[:lang] = "FRE"

    Limitations:

    • Only ID3v2 version 2.3 is supported for writing.
    • ID3v2 tags are always written using UTF-16 encoding.
    require "mp3info"
    
    Mp3Info.open("myfile.mp3") do |mp3|
      # Access and set via method
      puts mp3.tag2.TIT2
      mp3.tag2.TIT2 = "new TIT2"
    
      # Access via string key
      puts mp3.tag2["TIT2"]
    
      # Handling COMM tags with language options
      mp3.tag2.options[:lang] = "FRE"
      mp3.tag2.COMM = "my comment in french, correctly handled when reading and writing"
    end
  6. Manipulate album art and pictures in ID3v2

    master

    You can extract, remove, or add images (APIC tags) using tag2.

    Extracting images: m.tag2.pictures returns an array of [description, data]. The description typically ends with .jpg or .png to facilitate saving to disk.

    Adding images: Use m.tag2.add_picture(binary_data, options).

    • Note: Only one image is permitted per MP3 for compatibility; add_picture overwrites existing images.
    • MIME type: The MIME type is guessed from the input, but you can specify it via the :mime option. If using :mime, provide only the base type (e.g., 'jpeg', 'gif', or 'png'); the library prepends image/ automatically.
    • Options: You can pass pic_type (e.g., 0) in the options hash.

    Removing images: Use m.tag2.remove_pictures to clear all images.

    require "mp3info"
    
    file = File.new('input_img','rb')
    Mp3Info.open '1.mp3' do |m|
      # Extracting pictures
      pictures = m.tag2.pictures
      pictures.each do |description, data|
         File.binwrite(description, data)
      end
    
      # Removing all pictures
      m.tag2.remove_pictures
    
      # Adding a single picture
      m.tag2.add_picture(file.read)
    
      # Adding a picture with specific options
      # m.tag2.add_picture(file.read, mime: 'jpeg', pic_type: 3)
    end
  7. Read and write ID3v1 and ID3v2 tags using Mp3Info#tag

    master

    The Mp3Info#tag attribute provides access to standard tags. When reading, ID3v2 tags take priority over ID3v1 tags. When writing, both tag versions are updated.

    Commonly used attributes include:

    • title
    • artist
    • album
    • tracknum

    Changes are persisted to the file when Mp3Info#close is called or when the Mp3Info.open block terminates.

    require "mp3info"
    
    Mp3Info.open("myfile.mp3") do |mp3|
      puts mp3.tag.title
      puts mp3.tag.artist
      puts mp3.tag.album
      puts mp3.tag.tracknum
    
      mp3.tag.title = "track title"
      mp3.tag.artist = "artist name"
    end
  8. Iterate over MPEG frames

    master

    The #each_frame method allows you to iterate over every MPEG frame in the file. This is useful for low-level audio analysis or building tools like frame counters or cutters.

    Each yielded frame is a Hash containing:

    • :layer
    • :bitrate
    • :samplerate
    • :mpeg_version
    • :padding (boolean)
    • :size (size in bytes)
    info = Mp3Info.new("song.mp3")
    info.each_frame do |frame|
      puts "Frame size: #{frame[:size]} bytes"
    end
  9. Manage attached pictures (APIC) in ID3v2 tags

    master

    The ID3v2 class provides methods to add, retrieve, and remove attached pictures (APIC frames).

    Adding a picture

    Use add_picture(data, opts) where data is the binary string of the image.

    Options:

    • :pic_type (Integer): The ID3v2 picture type (0-14).
    • :mime (String): The MIME type (e.g., 'jpg', 'png', 'gif'). If not provided, it is guessed from the data.
    • :description (String): A description for the image.

    Retrieving pictures

    Calling pictures returns an array of images. Each image is represented as an array: [filename, binary_data].

    Removing pictures

    remove_pictures clears both APIC and PIC tags.

    # Adding a picture
    id3.add_picture(image_binary_string, mime: 'png', description: 'Album Art')
    
    # Retrieving pictures
    id3.pictures.each do |filename, data|
      File.open(filename, 'wb') { |f| f.write(data) }
    end
    
    # Removing pictures
    id3.remove_pictures
  10. Parse ID3v2 tags from an IO object

    master

    To populate an ID3v2 instance with data from a file, use the from_io(io) method. The io object must support the #seek() method.

    Note: This method sets the @io_position attribute, which indicates the position in the file where the tag ends.

    File.open('song.mp3', 'rb') do |file|
      id3 = ID3v2.new
      id3.from_io(file)
      puts id3["TIT2"]
    end
  11. Access MP3 audio properties

    master

    The Mp3Info class provides several reader methods to access the technical properties of the MPEG audio stream:

    • mpeg_version: The MPEG version (1 or 2).
    • layer: The MPEG layer (1, 2, or 3).
    • bitrate: The bitrate in kbps.
    • samplerate: The sample rate in Hz.
    • channel_mode: The channel mode (e.g., "Stereo", "JStereo", "Dual Channel", "Single Channel").
    • vbr: Boolean indicating if the file is Variable Bitrate.
    • length: The duration of the audio in seconds (Float).
    • header: A hash representing values in the MP3 frame header (e.g., :private, :copyright, :original, :padding, :error_protection, :mode_extension, :emphasis).
    • error_protection: Boolean indicating if error protection is present.