Module: Playlist::Format::M3U

Defined in:
lib/playlist/format/m3u.rb

Overview

Module to parse and generate M3U playlists

Class Method Summary collapse

Class Method Details

.generate(playlist) ⇒ String

Generate a M3U file from a [Playlist]

Parameters:

  • playlist (Playlist)

    the playlist to be converted to M3U

Returns:

  • (String)

    M3U as a string



30
31
32
33
34
35
36
37
38
# File 'lib/playlist/format/m3u.rb', line 30

def generate(playlist)
  text = "#EXTM3U\n"
  playlist.tracks.each do |t|
    duration = (t.duration / 1000).round
    text += "#EXTINF:#{duration},#{t.artist} - #{t.title}\n"
    text += "#{t.location}\n"
  end
  text
end

.parse(input) ⇒ Playlist

Parse a M3U file into a [Playlist]

Parameters:

  • input

    any object that responds to #each_line (either a String or a IO object)

Returns:



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/playlist/format/m3u.rb', line 8

def parse(input)
  Playlist.new do |playlist|
    track = Playlist::Track.new
    input.each_line do |line|
      if (matches = line.match(/^#EXTINF:(-?\d+),\s*(.+?)\s*-\s*(.+?)\s*$/))
        track.duration = matches[1].to_i * 1000
        track.creator = matches[2]
        track.title = matches[3]
      else
        if line =~ /^[^#]\S+.+\s*$/
          track.location = line.strip
          playlist.add_track(track)
        end
        track = Playlist::Track.new
      end
    end
  end
end