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 dsfml.audio.soundfile;
23 import dsfml.audio.sound;
24 
25 import dsfml.system.inputstream;
26 import dsfml.system.time;
27 
28 import std.stdio;
29 
30 import std..string;
31 
32 import std.algorithm;
33 import std.array;
34 
35 //import core.memory;
36 
37 import dsfml.system.err;
38 
39 /++
40  + Storage for audio samples defining a sound.
41  + 
42  + 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.
43  + 
44  + 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.
45  + 
46  + 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, ...). 
47  + 
48  + 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.
49  + 
50  + 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).
51  + 
52  + See_Also: http://www.sfml-dev.org/documentation/2.0/classsf_1_1SoundBuffer.php#details
53  + Authors: Laurent Gomila, Jeremy DeHaan
54  +/
55 class SoundBuffer
56 {
57 	package sfSoundBuffer* sfPtr;
58 
59 	this()
60 	{
61 		import dsfml.system..string;
62 		sfPtr = sfSoundBuffer_construct();
63 		err.write(toString(sfErr_getOutput()));
64 	}
65 
66 	~this()
67 	{
68 		import dsfml.system.config;
69 		mixin(destructorOutput);
70 		sfSoundBuffer_destroy(sfPtr);
71 	}
72 	
73 	//TODO: copy constructor?
74 	//So many possible properties....
75 
76 	/** 
77 	 * Get the array of audio samples stored in the buffer.
78 	 * 
79 	 *  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.
80 	 * 
81 	 *  Returns: Read-only pointer to the array of sound samples
82 	 */
83 	const(short[]) getSamples() const
84 	{
85 		if(sfSoundBuffer_getSampleCount(sfPtr) > 0)
86 		{
87 			return sfSoundBuffer_getSamples(sfPtr)[0 .. sfSoundBuffer_getSampleCount(sfPtr)];
88 		}
89 		else
90 		{
91 			return null;
92 		}
93 	}
94 
95 	/**
96 	 * Get the sample rate of the sound.
97 	 * 
98 	 * 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).
99 	 * 
100 	 * Returns: Sample rate (number of samples per second)
101 	 */
102 	uint getSampleRate() const
103 	{
104 		return sfSoundBuffer_getSampleRate(sfPtr);
105 	}
106 
107 	/**
108 	 * Get the number of channels used by the sound.
109 	 * 
110 	 * If the sound is mono then the number of channels will be 1, 2 for stereo, etc.
111 	 * 
112 	 * Returns: Number of channels
113 	 */
114 	uint getChannelCount() const
115 	{
116 		return sfSoundBuffer_getChannelCount(sfPtr);
117 	}
118 
119 	/**
120 	 * Get the total duration of the sound.
121 	 * 
122 	 * Returns: Sound duration
123 	 */
124 	Time getDuration() const
125 	{
126 		return microseconds(sfSoundBuffer_getDuration(sfPtr));
127 	}
128 
129 	/**
130 	 * Load the sound buffer from a file.
131 	 * 
132 	 * 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.
133 	 * 
134 	 * Params:
135 	 * 		filename =	Path of the sound file to load
136 	 * 
137 	 * Returns: True if loading succeeded, false if it failed
138 	 */
139 	bool loadFromFile(string filename)
140 	{
141     	import dsfml.system..string;
142 		if(sfSoundBuffer_loadFromFile(sfPtr, toStringz(filename)))
143 		{
144 		    return true;
145 		}
146 		else
147 		{
148 			err.write(toString(sfErr_getOutput()));
149 			return false;
150 		}
151 	}
152 
153 	/**
154 	 * Load the sound buffer from a file in memory.
155 	 * 
156 	 * 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.
157 	 * 
158 	 * Params:
159 	 * 		data =	The array of data
160 	 * 
161 	 * Returns: True if loading succeeded, false if it failed
162 	 */
163 	bool loadFromMemory(const(void)[] data)
164 	{
165 		if(sfSoundBuffer_loadFromMemory(sfPtr, data.ptr, data.length))
166 		{
167 		    return true;
168 		}
169 		else
170 		{
171 		    import dsfml.system..string;
172 			err.write(toString(sfErr_getOutput()));
173 			return false;
174 		}
175 	}
176 
177 	/*
178 	 * Load the sound buffer from a custom stream.
179 	 * 
180 	 * 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.
181 	 * 
182 	 * Params:
183 	 * 		stream =	Source stream to read from
184 	 * 
185 	 * Returns: True if loading succeeded, false if it failed
186 	 */
187 	bool loadFromStream(InputStream stream)
188 	{	
189 		if(sfSoundBuffer_loadFromStream(sfPtr, new SoundBufferStream(stream)))
190 		{
191 			return true;
192 		}
193 		else
194 		{
195 			import dsfml.system..string;
196 			err.write(toString(sfErr_getOutput()));
197 			return false;
198 		}
199 	}
200 
201 	/**
202 	 * Load the sound buffer from an array of audio samples.
203 	 * 
204 	 * The assumed format of the audio samples is 16 bits signed integer (short).
205 	 * 
206 	 * Params:
207 	 * 		samples =	Array of samples in memory
208 	 * 		channelCount =	Number of channels (1 = mono, 2 = stereo, ...)
209 	 * 		sampleRate =	Sample rate (number of samples to play per second)
210 	 * 
211 	 * Returns: True if loading succeeded, false if it failed
212 	 */
213 	bool loadFromSamples(const(short[]) samples, uint channelCount, uint sampleRate)
214 	{
215 		if(sfSoundBuffer_loadFromSamples(sfPtr, samples.ptr, samples.length, channelCount, sampleRate))
216 		{
217 			return true;
218 		}
219 		else
220 		{
221 			import dsfml.system..string;
222 			err.write(toString(sfErr_getOutput()));
223 			return false;
224 		}
225 	}
226 
227 	/**
228 	 * Save the sound buffer to an audio file.
229 	 * 
230 	 * 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.
231 	 * 
232 	 * Params:
233 	 * 		filename =	Path of the sound file to write
234 	 * 
235 	 * Returns: True if saving succeeded, false if it failed
236 	 */
237 	bool saveToFile(string filename)
238 	{
239 		import dsfml.system..string;
240 		if(sfSoundBuffer_saveToFile(sfPtr, toStringz(filename)))
241 		{
242 			return true;
243 		}
244 		else
245 		{
246 
247 			err.write(toString(sfErr_getOutput()));
248 			return false;
249 		}
250 	}
251 	
252 
253 }
254 
255 unittest
256 {
257 	version(DSFML_Unittest_Audio)
258 	{
259 		import std.stdio;
260 
261 		writeln("Unit test for sound buffer");
262 
263 		auto soundbuffer = new SoundBuffer();
264 
265 		if(!soundbuffer.loadFromFile("res/TestSound.ogg"))
266 		{
267 			//error
268 			return;
269 		}
270 
271 		writeln("Sample Rate: ", soundbuffer.getSampleRate());
272 
273 		writeln("Channel Count: ", soundbuffer.getChannelCount());
274 
275 		writeln("Duration: ",soundbuffer.getDuration().asSeconds());
276 
277 		writeln("Sample Count: ",soundbuffer.getSamples().length);
278 
279 		//use sound buffer here
280 
281 		writeln();
282 	}
283 }
284 
285 
286 private extern(C++) interface sfmlInputStream
287 {
288 	long read(void* data, long size);
289 		
290 	long seek(long position);
291 		
292 	long tell();
293 		
294 	long getSize();
295 }
296 
297 
298 private class SoundBufferStream:sfmlInputStream
299 {
300 	private InputStream myStream;
301 
302 	this(InputStream stream)
303 	{
304 		myStream = stream;
305 	}
306 
307 	extern(C++)long read(void* data, long size)
308 	{
309 		return myStream.read(data[0..cast(size_t)size]);
310 	}
311 
312 	extern(C++)long seek(long position)
313 	{
314 		return myStream.seek(position);
315 	}
316 	
317 	extern(C++)long tell()
318 	{
319 		return myStream.tell();
320 	}
321 	
322 	extern(C++)long getSize()
323 	{
324 		return myStream.getSize();
325 	}
326 }
327 
328 package struct sfSoundBuffer;
329 
330 private extern(C):
331 
332 sfSoundBuffer* sfSoundBuffer_construct();
333 
334 bool sfSoundBuffer_loadFromFile(sfSoundBuffer* soundBuffer, const char* filename);
335 
336 bool sfSoundBuffer_loadFromMemory(sfSoundBuffer* soundBuffer, const void* data, size_t sizeInBytes);
337 
338 bool sfSoundBuffer_loadFromStream(sfSoundBuffer* soundBuffer, sfmlInputStream stream);
339 
340 bool sfSoundBuffer_loadFromSamples(sfSoundBuffer* soundBuffer, const short* samples, size_t sampleCount, uint channelCount, uint sampleRate);
341 
342 sfSoundBuffer* sfSoundBuffer_copy(const sfSoundBuffer* soundBuffer);
343 
344 void sfSoundBuffer_destroy(sfSoundBuffer* soundBuffer);
345 
346 bool sfSoundBuffer_saveToFile(const sfSoundBuffer* soundBuffer, const char* filename);
347 
348 const(short)* sfSoundBuffer_getSamples(const sfSoundBuffer* soundBuffer);
349 
350 size_t sfSoundBuffer_getSampleCount(const sfSoundBuffer* soundBuffer);
351 
352 uint sfSoundBuffer_getSampleRate(const sfSoundBuffer* soundBuffer);
353 
354 uint sfSoundBuffer_getChannelCount(const sfSoundBuffer* soundBuffer);
355 
356 long sfSoundBuffer_getDuration(const sfSoundBuffer* soundBuffer);
357 
358 const(char)* sfErr_getOutput();
359