summaryrefslogtreecommitdiff
path: root/bass_player.rb
blob: 9a1d90a9750f004e726f2c4371cbb73da5c1854a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
require 'qml'
require 'audioinfo'
require './models'

module BassPlayer
  VERSION = '0.1'
  class SongController
    include QML::Access
    register_to_qml

    property(:title) { '' }
    property(:duration) { '' }
    property(:current_song) { '' }
    property(:current_segment) { '' }
    property(:model) { QML::ArrayModel.new(:title, :duration) }
    property(:segment_model) {
      QML::ArrayModel.new(:name, :from, :to)
    }

    def initialize
      super()
      Song.all.each do |song|
        model << {
          title: song.title,
          duration: ms_to_time(song.duration)
        }
      end
    end

    def add(file_url, duration, metadata)
      path = file_url.split('file://').last
      AudioInfo.open(path) do |info|
        title = if info.title.empty?
                  File.basename(path)
                else
                  info.title
                end
        song = Song.create(
          title: title,
          duration: info.length * 1000,
          path: file_url
        )

        item = {
          title: song.title,
          duration: ms_to_time(song.duration)
        }
        model << item
      end
    end

    def song_selected(row)
      unless row.nil?
        self.current_song = model[row][:title]
      end

      segment_model.clear
      self.current_segment = nil

      song = Song.first(title: self.current_song)

      segments = Song.first(title: self.current_song).segments.map do |segment|
        {
          name: segment.name,
          from: ms_to_time(segment.from),
          to: ms_to_time(segment.to)
        }
      end


      for segment in segments
        segment_model << segment
      end
      return {
        path: song.path,
        duration: song.duration
      }
    end

    def segment_selected(row)
      song = Song.first(title: self.current_song)
      self.current_segment = song.segments[row.to_i].to_hash
    end

    def add_segment(name, from, to)
      song = Song.first(title: current_song)
      Segment.create(
        name: name, from: parse_time(from), to: parse_time(to),
        song_id: song.id
      )
      song_selected(nil)
    end

    def ms_to_time(ms)
      retval = Time.at(ms/1000).utc.strftime("%M:%S")
      return retval
    end

    def parse_time(string)
      # Parses a string of the form '3:12' to milliseconds
      min, sec = string.split(':').map(&:to_i)
      return ((min * 60) + sec) * 1000
    end
  end
end

QML.run do |app|
  app.load_path Pathname(__FILE__) + '../main.qml'
end