summaryrefslogtreecommitdiff
path: root/bass_player.rb
blob: 6cb73c453255695f5c3b6822432d4fac9f1e4973 (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
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) { 0 }
    property(:model) { QML::ArrayModel.new(:title, :duration) }
    property(:part_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(song)
      puts "Selected song: #{song}"
      unless song.nil?
        self.current_song = model[song][:title]
        puts "Setting current song to #{self.current_song}"
      end
      part_model.clear
      parts = Song.first(title: self.current_song).parts.map do |part|
        {
          name: part.name,
          from: ms_to_time(part.from),
          to: ms_to_time(part.to)
        }
      end

      for part in parts
        part_model << part
      end
    end

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

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

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