audio_waveform-ruby 1.0.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: b59f3197bce64e87040f8f21d501027a21bfdffa
4
+ data.tar.gz: b5b2e04ffa3ce3085542f65d419885a9e2896592
5
+ SHA512:
6
+ metadata.gz: 1d70deefc853262ceb4cb1c2670c6c417c7440c8fae0cb6cb0cfac6b5fff4861088bdfd1cd32b0124fccbbad8dc1ae6d421bb3e089939da3e21ab9c7ce80c71a
7
+ data.tar.gz: d1ef99d028155f8dc6dddf15c5ff3470ea7635570b784ab43b62e46508847375d67cbb08c98e351680df8b447f703df052eef46b07a0e42f6079bde6ac8e2c1b
data/COPYING ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/ChangeLog ADDED
@@ -0,0 +1,3 @@
1
+ 2013-10-14 Chris Needham <chris.needham@bbc.co.uk>
2
+
3
+ * v1.0.1, initial public release
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in audio_waveform.gemspec
4
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,36 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ audio_waveform-ruby (1.0.1)
5
+ json
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ diff-lcs (1.2.4)
11
+ json (1.8.0)
12
+ multi_json (1.8.1)
13
+ redcarpet (3.0.0)
14
+ rspec (2.14.1)
15
+ rspec-core (~> 2.14.0)
16
+ rspec-expectations (~> 2.14.0)
17
+ rspec-mocks (~> 2.14.0)
18
+ rspec-core (2.14.5)
19
+ rspec-expectations (2.14.3)
20
+ diff-lcs (>= 1.1.3, < 2.0)
21
+ rspec-mocks (2.14.3)
22
+ simplecov (0.7.1)
23
+ multi_json (~> 1.0)
24
+ simplecov-html (~> 0.7.1)
25
+ simplecov-html (0.7.1)
26
+ yard (0.8.7.2)
27
+
28
+ PLATFORMS
29
+ ruby
30
+
31
+ DEPENDENCIES
32
+ audio_waveform-ruby!
33
+ redcarpet
34
+ rspec
35
+ simplecov
36
+ yard
data/README.md ADDED
@@ -0,0 +1,91 @@
1
+ # audio_waveform-ruby
2
+
3
+ The audio_waveform-ruby gem provides a Ruby API for access to audio waveform data
4
+ files generated by the [audiowaveform](https://github.com/bbcrd/audiowaveform) program.
5
+
6
+ Refer to the [audiowaveform](https://github.com/bbcrd/audiowaveform) documentation for more information and [this page](https://github.com/bbcrd/audiowaveform/blob/master/doc/DataFormat.md) for file format details.
7
+
8
+ ## Installation
9
+
10
+ To install:
11
+
12
+ $ gem install audio_waveform-ruby
13
+
14
+ or, if using bundler, add this line to your application's Gemfile:
15
+
16
+ gem 'audio_waveform'
17
+
18
+ gem 'audio_waveform-ruby', :require => 'audio_waveform', :git => 'https://github.com/bbcrd/audio_waveform-ruby.git'
19
+
20
+ and run
21
+
22
+ $ bundle install
23
+
24
+ ## Usage
25
+
26
+ To use this Gem in your program, add:
27
+
28
+ require 'audio_waveform'
29
+
30
+ Then, to load and use data from an existing waveform data file:
31
+
32
+ waveform = AudioWaveform::WaveformDataFile.new(filename: "test.dat")
33
+
34
+ puts waveform.sample_rate # Returns audio sample rate, in Hz
35
+ puts waveform.bits # Returns resolution of waveform data points
36
+ puts waveform.samples_per_pixel # Returns waveform zoom level, in samples per pixel
37
+ puts waveform.length # Returns number of waveform data points
38
+
39
+ (0...waveform.length).each do |i|
40
+ puts waveform.min(i) # Returns waveform minimum at index i
41
+ puts waveform.max(i) # Returns waveform maximum at index i
42
+ end
43
+
44
+ To generate a binary representation of a waveform data file:
45
+
46
+ waveform = AudioWaveform::WaveformDataFile.new(filename: "test.dat")
47
+ data = waveform.to_binary
48
+
49
+ To save waveform data as a file in binary format:
50
+
51
+ waveform = AudioWaveform::WaveformDataFile.new(filename: "test.dat")
52
+ waveform.save_as_binary("output.dat")
53
+
54
+ To generate a JSON representation of a waveform data file:
55
+
56
+ waveform = AudioWaveform::WaveformDataFile.new(filename: "test.dat")
57
+ waveform.to_json
58
+
59
+ To save waveform data as a file in JSON format:
60
+
61
+ waveform = AudioWaveform::WaveformDataFile.new(filename: "test.dat")
62
+ waveform.save_as_json("output.json")
63
+
64
+ To create a new waveform data file:
65
+
66
+ waveform = AudioWaveform::WaveformDataFile.new(
67
+ sample_rate: 44100,
68
+ samples_per_pixel: 512,
69
+ bits: 8
70
+ )
71
+
72
+ waveform.append(-10, 10)
73
+ .append(-11, 11)
74
+ .append(-3, 3)
75
+ # etc
76
+
77
+ ## License
78
+
79
+ See COPYING for details.
80
+
81
+ ## Contributing
82
+
83
+ If you have a feature request or want to report a bug, we'd be happy to hear from you. Please either raise an [issue](https://github.com/bbcrd/audio_waveform-ruby/issues), or fork the project and send us a pull request.
84
+
85
+ ## Authors
86
+
87
+ This software was written by [Chris Needham](https://github.com/chrisn), chris.needham at bbc.co.uk.
88
+
89
+ ## Copyright
90
+
91
+ Copyright 2013 British Broadcasting Corporation
data/Rakefile ADDED
@@ -0,0 +1,25 @@
1
+ require "bundler/gem_tasks"
2
+
3
+ require 'rspec/core/rake_task'
4
+ require 'yard'
5
+
6
+ task :default => :test
7
+
8
+ RSpec::Core::RakeTask.new(:test) do |t|
9
+ t.rspec_opts = ["--color"]
10
+ end
11
+
12
+ desc "Run tests with code coverage"
13
+ task :coverage do
14
+ ENV['COVERAGE'] = "true"
15
+ Rake::Task["test"].execute
16
+ end
17
+
18
+ YARD::Rake::YardocTask.new(:doc) do |t|
19
+ t.files = ['lib/**/*.rb']
20
+ t.options = [
21
+ '--output-dir', 'docs',
22
+ '--default-return', 'void',
23
+ '--readme', 'README.md'
24
+ ]
25
+ end
@@ -0,0 +1,25 @@
1
+ $:.unshift File.expand_path('../lib', __FILE__)
2
+
3
+ require 'audio_waveform/version'
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = "audio_waveform-ruby"
7
+ s.version = AudioWaveform::VERSION
8
+ s.authors = ["Chris Needham"]
9
+ s.email = ["chris.needham@bbc.co.uk"]
10
+ s.description = "The audiowaveform_ruby gem provides a Ruby API for access to audio waveform data files generated by the audiowaveform program"
11
+ s.summary = "Reads, writes, and rescales audio waveform data files"
12
+ s.homepage = "https://github.com/bbcrd/audio_waveform-ruby"
13
+
14
+ s.files = `git ls-files`.split($/)
15
+ s.test_files = s.files.grep(%r{^spec/audio_waveform/.*\.rb$})
16
+
17
+ s.require_paths = ["lib"]
18
+
19
+ s.add_dependency('json')
20
+
21
+ s.add_development_dependency('rspec')
22
+ s.add_development_dependency('simplecov')
23
+ s.add_development_dependency('redcarpet')
24
+ s.add_development_dependency('yard')
25
+ end
@@ -0,0 +1,8 @@
1
+ require "audio_waveform/error"
2
+ require "audio_waveform/waveform_data_file"
3
+ require "audio_waveform/version"
4
+
5
+ # AudioWaveform Ruby gem. See README.md for usage information.
6
+ #
7
+ module AudioWaveform
8
+ end
@@ -0,0 +1,7 @@
1
+ module AudioWaveform
2
+
3
+ # AudioWaveform exception class.
4
+ #
5
+ class Error < ::Exception
6
+ end
7
+ end
@@ -0,0 +1,6 @@
1
+ module AudioWaveform
2
+
3
+ # AudioWaveform gem version.
4
+ #
5
+ VERSION = "1.0.1"
6
+ end
@@ -0,0 +1,287 @@
1
+ require 'json'
2
+
3
+ module AudioWaveform
4
+
5
+ # Provides access to audio waveform data, and serialization to and from
6
+ # binary and JSON data formats.
7
+ #
8
+ class WaveformDataFile
9
+
10
+ # @param args [Hash]
11
+ #
12
+ # @option args [String] :filename Loads the specified binary waveform data
13
+ # file.
14
+ #
15
+ # @option args [Integer] :sample_rate
16
+ # @option args [Integer] :samples_per_pixel
17
+ # @option args [Integer] :bits
18
+ # @option args [Numeric, nil] :start_time Start time, in seconds, or nil
19
+ # if no start time to be set.
20
+ #
21
+ def initialize(args)
22
+ if args[:filename]
23
+ read(args[:filename])
24
+ else
25
+ self.sample_rate = args[:sample_rate]
26
+ self.samples_per_pixel = args[:samples_per_pixel]
27
+ self.bits = args[:bits]
28
+ self.start_time = args[:start_time]
29
+
30
+ @data = []
31
+ end
32
+ end
33
+
34
+ # @return [Integer] Audio sample rate, in Hz.
35
+ #
36
+ def sample_rate
37
+ @sample_rate
38
+ end
39
+
40
+ # @param sample_rate [Integer] Audio sample rate, in Hz. Must be greater
41
+ # than zero.
42
+ #
43
+ def sample_rate=(sample_rate)
44
+ if sample_rate <= 0
45
+ raise Error, "Invalid sample rate: #{sample_rate}"
46
+ else
47
+ @sample_rate = sample_rate
48
+ end
49
+ end
50
+
51
+ # @return [Integer] Number of audio samples per waveform minimum/maximum
52
+ # pair.
53
+ #
54
+ def samples_per_pixel
55
+ @samples_per_pixel
56
+ end
57
+
58
+ # Sets the waveform data scaling.
59
+ #
60
+ # @param samples_per_pixel [Integer] Number of audio samples per waveform
61
+ # minimum/maximum pair.
62
+ #
63
+ def samples_per_pixel=(samples_per_pixel)
64
+ if samples_per_pixel <= 0
65
+ raise Error, "Invalid samples per pixel: #{samples_per_pixel}"
66
+ else
67
+ @samples_per_pixel = samples_per_pixel
68
+ end
69
+ end
70
+
71
+ # @return [Integer] Resolution of waveform data points, either 8 or 16 bits.
72
+ #
73
+ def bits
74
+ @bits
75
+ end
76
+
77
+ # Sets the resolution of waveform data points.
78
+ #
79
+ # @param bits [Integer] Number of bits, must be either 8 or 16 bits
80
+ #
81
+ def bits=(bits)
82
+ if bits != 8 && bits != 16
83
+ raise Error, "Invalid bits: #{bits}"
84
+ else
85
+ @bits = bits
86
+ end
87
+ end
88
+
89
+ # @return [Numeric, nil] Start time of the waveform data, in seconds, or
90
+ # nil if not set.
91
+ #
92
+ def start_time
93
+ @start_time
94
+ end
95
+
96
+ #
97
+ # Sets the start time of the waveform data.
98
+ #
99
+ # @param start_time [Numeric, nil] Start time of the waveform data, in
100
+ # seconds, or nil if none.
101
+ #
102
+ def start_time=(start_time)
103
+ if start_time.nil?
104
+ @start_time = nil
105
+ elsif start_time < 0
106
+ raise Error, "Invalid start time: #{start_time}"
107
+ else
108
+ @start_time = start_time
109
+ end
110
+ end
111
+
112
+ # Writes the waveform data to file in JSON format.
113
+ #
114
+ # @param filename [String] The name of the file to write.
115
+ # @return [WaveformDataFile] The current object.
116
+ #
117
+ def save_as_json(filename)
118
+ File.open(filename, "w") do |file|
119
+ file.write(to_json)
120
+ end
121
+
122
+ self
123
+ end
124
+
125
+ # Writes the waveform data to file in binary (.dat) format.
126
+ #
127
+ # @param filename [String] The name of the file to write.
128
+ # @return [WaveformDataFile] The current object.
129
+ #
130
+ def save_as_binary(filename)
131
+ File.open(filename, "wb") do |file|
132
+ file.write(to_binary)
133
+ end
134
+
135
+ self
136
+ end
137
+
138
+ # @return [Hash] A hash representation of the waveform data file.
139
+ #
140
+ def to_hash
141
+ obj = {
142
+ sample_rate: @sample_rate,
143
+ bits: @bits,
144
+ samples_per_pixel: @samples_per_pixel,
145
+ length: @data.size / 2,
146
+ data: @data
147
+ }
148
+
149
+ if @start_time
150
+ obj[:start_time] = @start_time
151
+ end
152
+
153
+ obj
154
+ end
155
+
156
+ # @return [String] A JSON representation of the waveform data file.
157
+ #
158
+ def to_json
159
+ JSON.generate(to_hash)
160
+ end
161
+
162
+ # @return [String] A binary representation of the waveform data file.
163
+ #
164
+ def to_binary
165
+ if @bits == 8
166
+ flags = FLAG_8_BIT
167
+ format = "c*"
168
+ else
169
+ flags = 0
170
+ format = "s*"
171
+ end
172
+
173
+ output = encode_header(1, flags, @sample_rate, @samples_per_pixel, size)
174
+ output += @data.pack(format)
175
+ output
176
+ end
177
+
178
+ # Appends a waveform minimum/maximum pair.
179
+ #
180
+ # @param min_sample [Integer] Minimum audio sample amplitude value.
181
+ # @param max_sample [Integer] Maximum audio sample amplitude value.
182
+ #
183
+ # @return [WaveformDataFile] The current object.
184
+ #
185
+ def append(min_sample, max_sample)
186
+ @data << min_sample
187
+ @data << max_sample
188
+
189
+ self
190
+ end
191
+
192
+ # @return [Integer] The minimum waveform data point at the specified index.
193
+ #
194
+ def min_sample(index)
195
+ @data[2 * index]
196
+ end
197
+
198
+ # @return [Integer] The maximum waveform data point at the specified index.
199
+ #
200
+ def max_sample(index)
201
+ @data[2 * index + 1]
202
+ end
203
+
204
+ # @return [Integer] Length of waveform data (number of minimum/maximum
205
+ # value pairs).
206
+ #
207
+ def size
208
+ @data.size / 2
209
+ end
210
+
211
+ private
212
+
213
+ # Header format:
214
+ # version - 4 byte signed integer
215
+ # flags - 4 byte unsigned integer
216
+ # sample_rate - 4 byte signed integer
217
+ # samples_per_pixel - 4 byte signed integer
218
+ # size - 4 byte unsigned integer
219
+
220
+ HEADER_FORMAT = "lLllL"
221
+ HEADER_SIZE = 20
222
+ FLAG_8_BIT = 1
223
+
224
+ def read(filename)
225
+ # TODO: loading of JSON data from file
226
+
227
+ File.open(filename, "rb") do |file|
228
+ size = read_header(file)
229
+ read_data(file, size)
230
+ end
231
+ end
232
+
233
+ def encode_header(version, flags, sample_rate, samples_per_pixel, size)
234
+ [version, flags, sample_rate, samples_per_pixel, size].pack(HEADER_FORMAT)
235
+ end
236
+
237
+ def decode_header(header)
238
+ header.unpack(HEADER_FORMAT)
239
+ end
240
+
241
+ # @param file [File] The input file to read from.
242
+ # @return [Integer] Number of waveform data points, from Length header field.
243
+ #
244
+ def read_header(file)
245
+ header = file.read(HEADER_SIZE)
246
+
247
+ if header.nil? || header.bytesize != HEADER_SIZE
248
+ raise Error, "Failed to read file header"
249
+ end
250
+
251
+ version, flags, self.sample_rate, self.samples_per_pixel, size = decode_header(header)
252
+
253
+ if version != 1
254
+ raise Error, "Cannot load data file version: #{version}"
255
+ end
256
+
257
+ if (flags & FLAG_8_BIT) != 0
258
+ @bits = 8
259
+ else
260
+ @bits = 16
261
+ end
262
+
263
+ size
264
+ end
265
+
266
+ # @param file [File] The input file to read from.
267
+ # @param size [Integer] Number of waveform data points to read.
268
+ #
269
+ def read_data(file, size)
270
+ if @bits == 8
271
+ format = 'c*' # Array of 8-bit signed integers
272
+ elsif @bits == 16
273
+ format = 's*' # Array of 16-bit signed integers
274
+ end
275
+
276
+ length = size * (@bits / 8) * 2
277
+
278
+ raw_data = file.read(length)
279
+
280
+ if raw_data
281
+ @data = raw_data.unpack(format)
282
+ else
283
+ @data = []
284
+ end
285
+ end
286
+ end
287
+ end
@@ -0,0 +1,9 @@
1
+ require 'spec_helper'
2
+
3
+ describe AudioWaveform do
4
+ describe "version" do
5
+ it "should return version number" do
6
+ AudioWaveform::VERSION.should match %r{^(\d+)(\.(\d+)){2}$}
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,393 @@
1
+ require 'spec_helper'
2
+
3
+ require 'tempfile'
4
+ require 'tmpdir'
5
+
6
+ describe AudioWaveform::WaveformDataFile do
7
+ context "with valid 8-bit data file" do
8
+ let(:filename) { "spec/data/test_file_stereo_8bit_64spp.dat" }
9
+ let(:file) { AudioWaveform::WaveformDataFile.new(filename: filename) }
10
+
11
+ describe "to_binary" do
12
+ it "should return binary data" do
13
+ output = file.to_binary
14
+
15
+ output.bytesize.should == 3620
16
+
17
+ expected = Digest::MD5.hexdigest(File.read(filename))
18
+ actual = Digest::MD5.hexdigest(output)
19
+
20
+ actual.should == expected
21
+
22
+ fields = output.unpack("lLllL")
23
+ fields[0].should == 1 # version
24
+ fields[1].should == 1 # flags (8-bit)
25
+ fields[2].should == 16000
26
+ fields[3].should == 64
27
+ fields[4].should == 1800
28
+ end
29
+ end
30
+
31
+ describe "save_as_binary" do
32
+ let(:temp_filename) {
33
+ File.join(Dir.tmpdir, Dir::Tmpname.make_tmpname("waveform", 1))
34
+ }
35
+
36
+ after do
37
+ File.unlink(temp_filename)
38
+ end
39
+
40
+ it "should write binary data to a file" do
41
+ result = file.save_as_binary(temp_filename)
42
+ result.should == file
43
+
44
+ data = File.open(temp_filename, "rb") { |f| f.read }
45
+
46
+ data.bytesize.should == 3620
47
+ end
48
+ end
49
+
50
+ describe "to_json" do
51
+ it "should return JSON data" do
52
+ output = file.to_json
53
+
54
+ data = JSON.parse(output)
55
+
56
+ data.should have_key("sample_rate")
57
+ data["sample_rate"].should == 16000
58
+
59
+ data.should have_key("samples_per_pixel")
60
+ data["samples_per_pixel"].should == 64
61
+
62
+ data.should have_key("bits")
63
+ data["bits"].should == 8
64
+
65
+ data.should have_key("length")
66
+ data["length"].should == 1800
67
+
68
+ data.should have_key("data")
69
+ data["data"].should be_instance_of(Array)
70
+ data["data"].size.should == 3600
71
+ end
72
+ end
73
+
74
+ describe "save_as_json" do
75
+ let(:temp_filename) {
76
+ File.join(Dir.tmpdir, Dir::Tmpname.make_tmpname("waveform", 1))
77
+ }
78
+
79
+ after do
80
+ File.unlink(temp_filename)
81
+ end
82
+
83
+ it "should write JSON data to a file" do
84
+ result = file.save_as_json(temp_filename)
85
+ result.should == file
86
+
87
+ data = File.open(temp_filename, "rb") { |f| f.read }
88
+
89
+ obj = JSON.parse(data)
90
+ obj.should have_key("sample_rate")
91
+ obj.should have_key("samples_per_pixel")
92
+ obj.should have_key("bits")
93
+ obj.should have_key("length")
94
+ obj.should have_key("data")
95
+ end
96
+ end
97
+
98
+ describe "attributes" do
99
+ it "should return sample rate in hertz" do
100
+ file.sample_rate.should == 16000
101
+ end
102
+
103
+ it "should return samples per pixel" do
104
+ file.samples_per_pixel.should == 64
105
+ end
106
+
107
+ it "should return waveform data resolution in bits" do
108
+ file.bits.should == 8
109
+ end
110
+
111
+ it "should not have a start time" do
112
+ file.start_time.should be_nil
113
+ end
114
+
115
+ it "should return number of min and max waveform data pairs" do
116
+ file.size.should == 1800
117
+ end
118
+
119
+ it "should return waveform data" do
120
+ file.min_sample(0).should == 0
121
+ file.max_sample(0).should == 0
122
+
123
+ file.min_sample(26).should == -53
124
+ file.max_sample(26).should == 64
125
+
126
+ file.min_sample(206).should == 8
127
+ file.max_sample(206).should == 17
128
+
129
+ file.min_sample(217).should == -15
130
+ file.max_sample(217).should == -1
131
+
132
+ file.min_sample(1799).should == 0
133
+ file.max_sample(1799).should == 0
134
+ end
135
+ end
136
+ end
137
+
138
+ context "with valid 16-bit data file" do
139
+ let(:filename) { "spec/data/test_file_stereo_16bit_64spp.dat" }
140
+ let(:file) { AudioWaveform::WaveformDataFile.new(filename: filename) }
141
+
142
+ describe "attributes" do
143
+ it "should return sample rate in hertz" do
144
+ file.sample_rate.should == 16000
145
+ end
146
+
147
+ it "should return samples per pixel" do
148
+ file.samples_per_pixel.should == 64
149
+ end
150
+
151
+ it "should return waveform data resolution in bits" do
152
+ file.bits.should == 16
153
+ end
154
+
155
+ it "should not have a start time" do
156
+ file.start_time.should be_nil
157
+ end
158
+
159
+ it "should return number of min and max waveform data pairs" do
160
+ file.size.should == 1800
161
+ end
162
+
163
+ it "should return waveform data" do
164
+ file.min_sample(0).should == 0
165
+ file.max_sample(0).should == 0
166
+
167
+ file.min_sample(26).should == -13606
168
+ file.max_sample(26).should == 16602
169
+
170
+ file.min_sample(206).should == 2166
171
+ file.max_sample(206).should == 4512
172
+
173
+ file.min_sample(217).should == -4052
174
+ file.max_sample(217).should == -430
175
+
176
+ file.min_sample(1799).should == -8
177
+ file.max_sample(1799).should == 7
178
+ end
179
+ end
180
+ end
181
+
182
+ context "with a file containing no waveform data" do
183
+ let(:filename) { "spec/data/zero_length.dat" }
184
+ let(:file) { AudioWaveform::WaveformDataFile.new(filename: filename) }
185
+
186
+ describe "attributes" do
187
+ it "should return sample rate in hertz" do
188
+ file.sample_rate.should == 16000
189
+ end
190
+
191
+ it "should return samples per pixel" do
192
+ file.samples_per_pixel.should == 64
193
+ end
194
+
195
+ it "should return waveform data resolution in bits" do
196
+ file.bits.should == 8
197
+ end
198
+
199
+ it "should not have a start time" do
200
+ file.start_time.should be_nil
201
+ end
202
+
203
+ it "should return number of min and max waveform data pairs" do
204
+ file.size.should == 0
205
+ end
206
+ end
207
+ end
208
+
209
+ context "with a version 2 data file" do
210
+ let(:filename) { "spec/data/version2.dat" }
211
+
212
+ it "should not load the file" do
213
+ expect {
214
+ AudioWaveform::WaveformDataFile.new(filename: filename)
215
+ }.to raise_error(AudioWaveform::Error, "Cannot load data file version: 2")
216
+ end
217
+ end
218
+
219
+ context "with a file with invalid scale" do
220
+ let(:filename) { "spec/data/scale_too_low.dat" }
221
+
222
+ it "should not load the file" do
223
+ expect {
224
+ AudioWaveform::WaveformDataFile.new(filename: filename)
225
+ }.to raise_error(AudioWaveform::Error, "Invalid samples per pixel: 0")
226
+ end
227
+ end
228
+
229
+ context "with a file with invalid sample rate" do
230
+ let(:filename) { "spec/data/sample_rate_too_low.dat" }
231
+
232
+ it "should not load the file" do
233
+ expect {
234
+ AudioWaveform::WaveformDataFile.new(filename: filename)
235
+ }.to raise_error(AudioWaveform::Error, "Invalid sample rate: 0")
236
+ end
237
+ end
238
+
239
+ context "with a file with incomplete header" do
240
+ let(:filename) { "spec/data/invalid_header.dat" }
241
+
242
+ it "should not load the file" do
243
+ expect {
244
+ AudioWaveform::WaveformDataFile.new(filename: filename)
245
+ }.to raise_error(AudioWaveform::Error, "Failed to read file header")
246
+ end
247
+ end
248
+
249
+ context "with a newly created waveform data file" do
250
+ let(:file) {
251
+ AudioWaveform::WaveformDataFile.new(
252
+ sample_rate: 44100,
253
+ samples_per_pixel: 512,
254
+ bits: 16
255
+ )
256
+ }
257
+
258
+ describe "append" do
259
+ it "should append waveform data points" do
260
+ file.size.should == 0
261
+
262
+ file.append(-99, 101).append(-49, 51)
263
+
264
+ file.size.should == 2
265
+ file.min_sample(0).should == -99
266
+ file.max_sample(0).should == 101
267
+ file.min_sample(1).should == -49
268
+ file.max_sample(1).should == 51
269
+ end
270
+ end
271
+
272
+ describe "to_binary" do
273
+ it "should return binary data" do
274
+ output = file.to_binary
275
+
276
+ output.bytesize.should == 20
277
+
278
+ fields = output.unpack("lLllL")
279
+ fields[0].should == 1 # version
280
+ fields[1].should == 0 # flags (16-bit)
281
+ fields[2].should == 44100
282
+ fields[3].should == 512
283
+ fields[4].should == 0
284
+ end
285
+ end
286
+
287
+ describe "to_json" do
288
+ it "should return JSON string" do
289
+ output = file.to_json
290
+
291
+ data = JSON.parse(output)
292
+
293
+ data.should have_key("sample_rate")
294
+ data["sample_rate"].should == 44100
295
+
296
+ data.should have_key("samples_per_pixel")
297
+ data["samples_per_pixel"].should == 512
298
+
299
+ data.should have_key("bits")
300
+ data["bits"].should == 16
301
+
302
+ data.should have_key("length")
303
+ data["length"].should == 0
304
+
305
+ data.should have_key("data")
306
+ data["data"].should be_instance_of(Array)
307
+ data["data"].size.should == 0
308
+
309
+ data.should_not have_key("start_time")
310
+ end
311
+ end
312
+ end
313
+
314
+ context "with new waveform data file with start time" do
315
+ let(:file) {
316
+ AudioWaveform::WaveformDataFile.new(
317
+ sample_rate: 44100,
318
+ samples_per_pixel: 512,
319
+ bits: 16,
320
+ start_time: 8.5
321
+ )
322
+ }
323
+
324
+ describe "attributes" do
325
+ it "should return start time" do
326
+ file.start_time.should == 8.5
327
+ end
328
+ end
329
+
330
+ describe "to_json" do
331
+ it "should include start_time field in output" do
332
+ output = file.to_json
333
+
334
+ data = JSON.parse(output)
335
+
336
+ data.should have_key("start_time")
337
+ data["start_time"].should == 8.5
338
+ end
339
+ end
340
+
341
+ end
342
+
343
+ context "invalid constructor arguments" do
344
+ describe "bits" do
345
+ it "should raise exception if not 8 or 16" do
346
+ expect {
347
+ AudioWaveform::WaveformDataFile.new(
348
+ sample_rate: 44100,
349
+ samples_per_pixel: 512,
350
+ bits: 10
351
+ )
352
+ }.to raise_error(AudioWaveform::Error, %r{Invalid bits})
353
+ end
354
+ end
355
+
356
+ describe "sample_rate" do
357
+ it "should raise exception if too small" do
358
+ expect {
359
+ AudioWaveform::WaveformDataFile.new(
360
+ sample_rate: 0,
361
+ samples_per_pixel: 512,
362
+ bits: 8
363
+ )
364
+ }.to raise_error(AudioWaveform::Error, %r{Invalid sample rate})
365
+ end
366
+ end
367
+
368
+ describe "samples_per_pixel" do
369
+ it "should raise exception if too small" do
370
+ expect {
371
+ AudioWaveform::WaveformDataFile.new(
372
+ sample_rate: 44100,
373
+ samples_per_pixel: 0,
374
+ bits: 8
375
+ )
376
+ }.to raise_error(AudioWaveform::Error, %r{Invalid samples per pixel})
377
+ end
378
+ end
379
+
380
+ describe "start_time" do
381
+ it "should raise exception if less than zero" do
382
+ expect {
383
+ AudioWaveform::WaveformDataFile.new(
384
+ sample_rate: 44100,
385
+ samples_per_pixel: 512,
386
+ bits: 8,
387
+ start_time: -1.0
388
+ )
389
+ }.to raise_error(AudioWaveform::Error, %r{Invalid start time})
390
+ end
391
+ end
392
+ end
393
+ end
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,20 @@
1
+ require 'rubygems'
2
+ require 'bundler/setup'
3
+
4
+ require 'logger'
5
+
6
+ Bundler.require :test
7
+
8
+ if ENV['COVERAGE']
9
+ require 'simplecov'
10
+ SimpleCov.start do
11
+ # Exclude test code from coverage report
12
+ add_filter '/spec/'
13
+ add_filter '/vendor/'
14
+ end
15
+ end
16
+
17
+ # add lib to current path
18
+ $:.unshift(File.join(File.dirname(__FILE__), "..", "lib"))
19
+
20
+ require 'audio_waveform'
metadata ADDED
@@ -0,0 +1,138 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: audio_waveform-ruby
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Chris Needham
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2013-12-13 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: json
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - '>='
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - '>='
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rspec
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - '>='
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - '>='
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: simplecov
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - '>='
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - '>='
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: redcarpet
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - '>='
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - '>='
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: yard
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - '>='
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - '>='
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ description: The audiowaveform_ruby gem provides a Ruby API for access to audio waveform
84
+ data files generated by the audiowaveform program
85
+ email:
86
+ - chris.needham@bbc.co.uk
87
+ executables: []
88
+ extensions: []
89
+ extra_rdoc_files: []
90
+ files:
91
+ - COPYING
92
+ - ChangeLog
93
+ - Gemfile
94
+ - Gemfile.lock
95
+ - README.md
96
+ - Rakefile
97
+ - audio_waveform-ruby.gemspec
98
+ - lib/audio_waveform.rb
99
+ - lib/audio_waveform/error.rb
100
+ - lib/audio_waveform/version.rb
101
+ - lib/audio_waveform/waveform_data_file.rb
102
+ - spec/audio_waveform/version_spec.rb
103
+ - spec/audio_waveform/waveform_data_file_spec.rb
104
+ - spec/data/invalid_header.dat
105
+ - spec/data/sample_rate_too_low.dat
106
+ - spec/data/scale_too_low.dat
107
+ - spec/data/test_file_stereo_16bit_64spp.dat
108
+ - spec/data/test_file_stereo_8bit_64spp.dat
109
+ - spec/data/version2.dat
110
+ - spec/data/zero_length.dat
111
+ - spec/spec_helper.rb
112
+ homepage: https://github.com/bbcrd/audio_waveform-ruby
113
+ licenses: []
114
+ metadata: {}
115
+ post_install_message:
116
+ rdoc_options: []
117
+ require_paths:
118
+ - lib
119
+ required_ruby_version: !ruby/object:Gem::Requirement
120
+ requirements:
121
+ - - '>='
122
+ - !ruby/object:Gem::Version
123
+ version: '0'
124
+ required_rubygems_version: !ruby/object:Gem::Requirement
125
+ requirements:
126
+ - - '>='
127
+ - !ruby/object:Gem::Version
128
+ version: '0'
129
+ requirements: []
130
+ rubyforge_project:
131
+ rubygems_version: 2.0.3
132
+ signing_key:
133
+ specification_version: 4
134
+ summary: Reads, writes, and rescales audio waveform data files
135
+ test_files:
136
+ - spec/audio_waveform/version_spec.rb
137
+ - spec/audio_waveform/waveform_data_file_spec.rb
138
+ has_rdoc: