1 /**
2  * ae.ui.audio.memory.base
3  *
4  * License:
5  *   This Source Code Form is subject to the terms of
6  *   the Mozilla Public License, v. 2.0. If a copy of
7  *   the MPL was not distributed with this file, You
8  *   can obtain one at http://mozilla.org/MPL/2.0/.
9  *
10  * Authors:
11  *   Vladimir Panteleev <ae@cy.md>
12  */
13 
14 module ae.ui.audio.source.memory;
15 
16 import std.algorithm.comparison;
17 import std.algorithm.mutation;
18 import std.range;
19 import std.range.primitives;
20 
21 import ae.ui.audio.source.base;
22 
23 /// Implementation of `AbstractSoundSource` backed by a simple array of samples.
24 template MemorySoundSource(Sample)
25 {
26 	final class MemorySoundSource : AbstractSoundSource!Sample
27 	{
28 		Sample[] samples; ///
29 		uint sampleRate; ///
30 
31 		this(Sample[] samples, uint sampleRate)
32 		{
33 			this.samples = samples;
34 			this.sampleRate = sampleRate;
35 		} ///
36 
37 		override uint getSampleRate() const nothrow
38 		{
39 			return sampleRate;
40 		} ///
41 
42 		override size_t getNumChannels() const nothrow
43 		{
44 			// TODO
45 			return 1;
46 		} ///
47 
48 		override bool procedural() const nothrow
49 		{
50 			return false;
51 		} ///
52 
53 		override size_t copySamples(size_t channel, size_t start, Sample[] buffer) const nothrow
54 		{
55 			auto slice = getSamples(channel, start, buffer.length);
56 			buffer[0 .. slice.length] = slice;
57 			return slice.length;
58 		} ///
59 
60 		override const(Sample)[] getSamples(size_t channel, size_t start, size_t maxLength) const nothrow
61 		{
62 			start = min(start, samples.length);
63 			auto end = min(start + maxLength, samples.length);
64 			return samples[start .. end];
65 		} ///
66 	}
67 }
68 
69 /// Construct a `MemorySoundSource` from an array.
70 MemorySoundSource!Sample memorySoundSource(Sample)(Sample[] samples, uint sampleRate)
71 {
72 	return new MemorySoundSource!Sample(samples, sampleRate);
73 }
74 
75 unittest
76 {
77 	auto w = memorySoundSource([short.max, short.min], 44100);
78 }