Class: Player

Inherits:
Object
  • Object
show all
Defined in:
lib/mdisc/player.rb

Constant Summary collapse

WAIT_TIME =
0.5

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializePlayer

Returns a new instance of Player.



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/mdisc/player.rb', line 8

def initialize
  self.ui = Ui.new
  @datatype = 'songs'
  @mpg123_thread = nil
  @mpg123_pid = nil
  @playing_flag = false
  @pause_flag = false
  @songs = []
  @idx = 0
  @carousel = ->(left, right, x){x < left ? right : (x > right ? left : x)}
end

Instance Attribute Details

#uiObject

Returns the value of attribute ui.



6
7
8
# File 'lib/mdisc/player.rb', line 6

def ui
  @ui
end

Instance Method Details

#nextObject



85
86
87
88
89
90
91
# File 'lib/mdisc/player.rb', line 85

def next
  stop
  sleep WAIT_TIME

  @idx = @carousel[0, @songs.size - 1, @idx + 1]
  recall
end

#pauseObject



67
68
69
70
71
72
73
74
# File 'lib/mdisc/player.rb', line 67

def pause
  @pause_flag = true
  # send SIGSTOP to pipe
  Process.kill(:SIGSTOP, @mp3id)

  item = @songs[@idx]
  ui.build_playinfo(item['song_name'], item['artist'], true)
end

#play(datatype, songs, idx, switch_flag = false) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/mdisc/player.rb', line 38

def play(datatype, songs, idx, switch_flag = false)
  @datatype = datatype

  if !switch_flag
    @pause_flag ? resume : pause if @playing_flag
  elsif switch_flag
    @songs = songs
    @idx = idx
    @playing_flag ? switch : recall
  end
end

#prevObject



93
94
95
96
97
98
99
# File 'lib/mdisc/player.rb', line 93

def prev
  stop
  sleep WAIT_TIME

  @idx = @carousel[0, @songs.size - 1, @idx - 1]
  recall
end

#recallObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/mdisc/player.rb', line 20

def recall
  @playing_flag = true
  @pause_flag = false

  item = @songs[@idx]
  ui.build_playinfo(item['song_name'], item['artist'])

  @thread = Thread.new do
    @mp3id, stdin, stdout, stderr = Open4::popen4('mpg123', item['mp3_url'])
    Process::waitpid2 @mp3id

    if @playing_flag
      @idx = @carousel[0, @songs.size - 1, @idx + 1]
      recall
    end
  end
end

#resumeObject



76
77
78
79
80
81
82
83
# File 'lib/mdisc/player.rb', line 76

def resume
  @pause_flag = false
  # send SIGCONT to pipe
  Process.kill(:SIGCONT, @mp3id)

  item = @songs[@idx]
  ui.build_playinfo(item['song_name'], item['artist'])
end

#stopObject



56
57
58
59
60
61
62
63
64
65
# File 'lib/mdisc/player.rb', line 56

def stop
  return unless @playing_flag
  return unless @thread
  return unless @mp3id

  @playing_flag = false
  # kill this process and thread
  Process.kill(:SIGKILL, @mp3id)
  Thread.kill @thread
end

#switchObject



50
51
52
53
54
# File 'lib/mdisc/player.rb', line 50

def switch
  stop
  sleep WAIT_TIME
  recall
end