1 /*
2 DSFML - The Simple and Fast Multimedia Library for D
3 
4 Copyright (c) 2013 - 2015 Jeremy DeHaan (dehaan.jeremiah@gmail.com)
5 
6 This software is provided 'as-is', without any express or implied warranty.
7 In no event will the authors be held liable for any damages arising from the use of this software.
8 
9 Permission is granted to anyone to use this software for any purpose, including commercial applications,
10 and to alter it and redistribute it freely, subject to the following restrictions:
11 
12 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software.
13 If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
14 
15 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
16 
17 3. This notice may not be removed or altered from any source distribution
18 */
19 
20 module dsfml.audio.soundbuffer;
21 
22 import core.time;
23 
24 import dsfml.audio.soundfile;
25 import dsfml.audio.sound;
26 
27 import dsfml.system.inputstream;
28 
29 import std.stdio;
30 
31 import std.string;
32 
33 import std.algorithm;
34 import std.array;
35 
36 //import core.memory;
37 
38 import dsfml.system.err;
39 
40 /++
41  + Storage for audio samples defining a sound.
42  + 
43  + A sample is a 16 bits signed integer that defines the amplitude of the sound at a given time. The sound is then restituted by playing these samples at a high rate (for example, 44100 samples per second is the standard rate used for playing CDs). In short, audio samples are like texture pixels, and a SoundBuffer is similar to a Texture.
44  + 
45  + A sound buffer can be loaded from a file (see loadFromFile() for the complete list of supported formats), from memory, from a custom stream (see InputStream) or directly from an array of samples. It can also be saved back to a file.
46  + 
47  + Sound buffers alone are not very useful: they hold the audio data but cannot be played. To do so, you need to use the sf::Sound class, which provides functions to play/pause/stop the sound as well as changing the way it is outputted (volume, pitch, 3D position, ...). 
48  + 
49  + This separation allows more flexibility and better performances: indeed a sf::SoundBuffer is a heavy resource, and any operation on it is slow (often too slow for real-time applications). On the other side, a sf::Sound is a lightweight object, which can use the audio data of a sound buffer and change the way it is played without actually modifying that data. Note that it is also possible to bind several Sound instances to the same SoundBuffer.
50  + 
51  + It is important to note that the Sound instance doesn't copy the buffer that it uses, it only keeps a reference to it. Thus, a SoundBuffer must not be destructed while it is used by a Sound (i.e. never write a function that uses a local SoundBuffer instance for loading a sound).
52  + 
53  + See_Also: http://www.sfml-dev.org/documentation/2.0/classsf_1_1SoundBuffer.php#details
54  + Authors: Laurent Gomila, Jeremy DeHaan
55  +/
56 class SoundBuffer
57 {
58 	package sfSoundBuffer* sfPtr;
59 
60 	this()
61 	{
62 		import dsfml.system.string;
63 		sfPtr = sfSoundBuffer_construct();
64 		err.write(dsfml.system..string.toString(sfErr_getOutput()));
65 	}
66 
67 	~this()
68 	{
69 		import dsfml.system.config;
70 		mixin(destructorOutput);
71 		sfSoundBuffer_destroy(sfPtr);
72 	}
73 	
74 	//TODO: copy constructor?
75 	//So many possible properties....
76 
77 	/** 
78 	 * Get the array of audio samples stored in the buffer.
79 	 * 
80 	 *  The format of the returned samples is 16 bits signed integer (sf::Int16). The total number of samples in this array is given by the getSampleCount() function.
81 	 * 
82 	 *  Returns: Read-only pointer to the array of sound samples
83 	 */
84 	const(short[]) getSamples() const
85 	{
86 		if(sfSoundBuffer_getSampleCount(sfPtr) > 0)
87 		{
88 			return sfSoundBuffer_getSamples(sfPtr)[0 .. sfSoundBuffer_getSampleCount(sfPtr)];
89 		}
90 		else
91 		{
92 			return null;
93 		}
94 	}
95 
96 	/**
97 	 * Get the sample rate of the sound.
98 	 * 
99 	 * The sample rate is the number of samples played per second. The higher, the better the quality (for example, 44100 samples/s is CD quality).
100 	 * 
101 	 * Returns: Sample rate (number of samples per second)
102 	 */
103 	uint getSampleRate() const
104 	{
105 		return sfSoundBuffer_getSampleRate(sfPtr);
106 	}
107 
108 	/**
109 	 * Get the number of channels used by the sound.
110 	 * 
111 	 * If the sound is mono then the number of channels will be 1, 2 for stereo, etc.
112 	 * 
113 	 * Returns: Number of channels
114 	 */
115 	uint getChannelCount() const
116 	{
117 		return sfSoundBuffer_getChannelCount(sfPtr);
118 	}
119 
120 	/**
121 	 * Get the total duration of the sound.
122 	 * 
123 	 * Returns: Sound duration
124 	 */
125 	Duration getDuration() const
126 	{
127 		import core.time;
128 		return usecs(sfSoundBuffer_getDuration(sfPtr));
129 	}
130 
131 	/**
132 	 * Load the sound buffer from a file.
133 	 * 
134 	 * Here is a complete list of all the supported audio formats: ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam, w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
135 	 * 
136 	 * Params:
137 	 * 		filename =	Path of the sound file to load
138 	 * 
139 	 * Returns: True if loading succeeded, false if it failed
140 	 */
141 	bool loadFromFile(string filename)
142 	{
143     	import dsfml.system.string;
144 		if(sfSoundBuffer_loadFromFile(sfPtr, toStringz(filename)))
145 		{
146 		    return true;
147 		}
148 		else
149 		{
150 			err.write(dsfml.system..string.toString(sfErr_getOutput()));
151 			return false;
152 		}
153 	}
154 
155 	/**
156 	 * Load the sound buffer from a file in memory.
157 	 * 
158 	 * Here is a complete list of all the supported audio formats: ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam, w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
159 	 * 
160 	 * Params:
161 	 * 		data =	The array of data
162 	 * 
163 	 * Returns: True if loading succeeded, false if it failed
164 	 */
165 	bool loadFromMemory(const(void)[] data)
166 	{
167 		if(sfSoundBuffer_loadFromMemory(sfPtr, data.ptr, data.length))
168 		{
169 		    return true;
170 		}
171 		else
172 		{
173 		    import dsfml.system.string;
174 			err.write(dsfml.system..string.toString(sfErr_getOutput()));
175 			return false;
176 		}
177 	}
178 
179 	/*
180 	 * Load the sound buffer from a custom stream.
181 	 * 
182 	 * Here is a complete list of all the supported audio formats: ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam, w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
183 	 * 
184 	 * Params:
185 	 * 		stream =	Source stream to read from
186 	 * 
187 	 * Returns: True if loading succeeded, false if it failed
188 	 */
189 	bool loadFromStream(InputStream stream)
190 	{	
191 		if(sfSoundBuffer_loadFromStream(sfPtr, new SoundBufferStream(stream)))
192 		{
193 			return true;
194 		}
195 		else
196 		{
197 			import dsfml.system.string;
198 			err.write(dsfml.system..string.toString(sfErr_getOutput()));
199 			return false;
200 		}
201 	}
202 
203 	/**
204 	 * Load the sound buffer from an array of audio samples.
205 	 * 
206 	 * The assumed format of the audio samples is 16 bits signed integer (short).
207 	 * 
208 	 * Params:
209 	 * 		samples =	Array of samples in memory
210 	 * 		channelCount =	Number of channels (1 = mono, 2 = stereo, ...)
211 	 * 		sampleRate =	Sample rate (number of samples to play per second)
212 	 * 
213 	 * Returns: True if loading succeeded, false if it failed
214 	 */
215 	bool loadFromSamples(const(short[]) samples, uint channelCount, uint sampleRate)
216 	{
217 		if(sfSoundBuffer_loadFromSamples(sfPtr, samples.ptr, samples.length, channelCount, sampleRate))
218 		{
219 			return true;
220 		}
221 		else
222 		{
223 			import dsfml.system.string;
224 			err.write(dsfml.system..string.toString(sfErr_getOutput()));
225 			return false;
226 		}
227 	}
228 
229 	/**
230 	 * Save the sound buffer to an audio file.
231 	 * 
232 	 * Here is a complete list of all the supported audio formats: ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam, w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
233 	 * 
234 	 * Params:
235 	 * 		filename =	Path of the sound file to write
236 	 * 
237 	 * Returns: True if saving succeeded, false if it failed
238 	 */
239 	bool saveToFile(string filename)
240 	{
241 		import dsfml.system.string;
242 		if(sfSoundBuffer_saveToFile(sfPtr, toStringz(filename)))
243 		{
244 			return true;
245 		}
246 		else
247 		{
248 
249 			err.write(dsfml.system..string.toString(sfErr_getOutput()));
250 			return false;
251 		}
252 	}
253 	
254 
255 }
256 
257 unittest
258 {
259 	version(DSFML_Unittest_Audio)
260 	{
261 		import std.stdio;
262 
263 		writeln("Unit test for sound buffer");
264 
265 		auto soundbuffer = new SoundBuffer();
266 
267 		if(!soundbuffer.loadFromFile("res/TestSound.ogg"))
268 		{
269 			//error
270 			return;
271 		}
272 
273 		writeln("Sample Rate: ", soundbuffer.getSampleRate());
274 
275 		writeln("Channel Count: ", soundbuffer.getChannelCount());
276 
277 		writeln("Duration: ", soundbuffer.getDuration().total!"seconds");
278 
279 		writeln("Sample Count: ", soundbuffer.getSamples().length);
280 
281 		//use sound buffer here
282 
283 		writeln();
284 	}
285 }
286 
287 
288 private extern(C++) interface sfmlInputStream
289 {
290 	long read(void* data, long size);
291 		
292 	long seek(long position);
293 		
294 	long tell();
295 		
296 	long getSize();
297 }
298 
299 
300 private class SoundBufferStream:sfmlInputStream
301 {
302 	private InputStream myStream;
303 
304 	this(InputStream stream)
305 	{
306 		myStream = stream;
307 	}
308 
309 	extern(C++)long read(void* data, long size)
310 	{
311 		return myStream.read(data[0..cast(size_t)size]);
312 	}
313 
314 	extern(C++)long seek(long position)
315 	{
316 		return myStream.seek(position);
317 	}
318 	
319 	extern(C++)long tell()
320 	{
321 		return myStream.tell();
322 	}
323 	
324 	extern(C++)long getSize()
325 	{
326 		return myStream.getSize();
327 	}
328 }
329 
330 package struct sfSoundBuffer;
331 
332 private extern(C):
333 
334 sfSoundBuffer* sfSoundBuffer_construct();
335 
336 bool sfSoundBuffer_loadFromFile(sfSoundBuffer* soundBuffer, const char* filename);
337 
338 bool sfSoundBuffer_loadFromMemory(sfSoundBuffer* soundBuffer, const void* data, size_t sizeInBytes);
339 
340 bool sfSoundBuffer_loadFromStream(sfSoundBuffer* soundBuffer, sfmlInputStream stream);
341 
342 bool sfSoundBuffer_loadFromSamples(sfSoundBuffer* soundBuffer, const short* samples, size_t sampleCount, uint channelCount, uint sampleRate);
343 
344 sfSoundBuffer* sfSoundBuffer_copy(const sfSoundBuffer* soundBuffer);
345 
346 void sfSoundBuffer_destroy(sfSoundBuffer* soundBuffer);
347 
348 bool sfSoundBuffer_saveToFile(const sfSoundBuffer* soundBuffer, const char* filename);
349 
350 const(short)* sfSoundBuffer_getSamples(const sfSoundBuffer* soundBuffer);
351 
352 size_t sfSoundBuffer_getSampleCount(const sfSoundBuffer* soundBuffer);
353 
354 uint sfSoundBuffer_getSampleRate(const sfSoundBuffer* soundBuffer);
355 
356 uint sfSoundBuffer_getChannelCount(const sfSoundBuffer* soundBuffer);
357 
358 long sfSoundBuffer_getDuration(const sfSoundBuffer* soundBuffer);
359 
360 const(char)* sfErr_getOutput();