Class: Hallon::Fifo

Inherits:
Object
  • Object
show all
Defined in:
lib/hallon-fifo/fifo.rb,
lib/hallon-fifo/version.rb

Constant Summary collapse

VERSION =
"0.0.3"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeFifo

Returns a new instance of Fifo.



8
9
10
11
12
13
14
15
16
# File 'lib/hallon-fifo/fifo.rb', line 8

def initialize
	@buffer = Array.new
	@playing, @stopped = false
	@buffer_size = 22050 # overridden by format=

	@output ||= "hallon-fifo.pcm"
	File.delete(@output) if File.exists?(@output)
	File.mkfifo(@output) # Will error if it's overwriting another file
end

Instance Attribute Details

#formatObject

Returns the value of attribute format.



6
7
8
# File 'lib/hallon-fifo/fifo.rb', line 6

def format
  @format
end

#outputObject

Returns the value of attribute output.



6
7
8
# File 'lib/hallon-fifo/fifo.rb', line 6

def output
  @output
end

Instance Method Details

#dropsObject



31
32
33
34
35
# File 'lib/hallon-fifo/fifo.rb', line 31

def drops
	# This SHOULD return the number of times the queue "stuttered"
	# However, it ain't easy to do this with only knowledge of the fifo pipe.
	0
end

#pauseObject



37
38
39
# File 'lib/hallon-fifo/fifo.rb', line 37

def pause
	@playing = false
end

#playObject



41
42
43
44
# File 'lib/hallon-fifo/fifo.rb', line 41

def play
	@playing = true
	@stopped = false
end

#resetObject



53
54
55
# File 'lib/hallon-fifo/fifo.rb', line 53

def reset
	self.output = @output
end

#stopObject



46
47
48
49
50
51
# File 'lib/hallon-fifo/fifo.rb', line 46

def stop
	@stopped = true
	@stream_thread.exit if @stream_thread

	@buffer.clear
end

#streamObject

runs indefinitely



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
# File 'lib/hallon-fifo/fifo.rb', line 57

def stream # runs indefinitely
	@stream_thread = Thread.new do
		queue = File.new(@output, "wb")

		loop do

			start = Time.now.to_f
			complete = start + 0.5

			# Get the next block from Spotify.
			audio_data = yield(@buffer_size)

			if audio_data.nil? # Audio format has changed, reset buffer.
				@buffer.clear
			else
				@buffer += audio_data
				begin
					queue.syswrite packed_samples(@buffer)
				rescue Errno::EPIPE
			        self.reset
				end
				@buffer.clear
			end

			ensure_playing

			finish = Time.now.to_f
			sleep complete - finish if finish < complete
		end
	end
end