1 /* 2 Copyright © 2020, Luna Nielsen 3 Distributed under the 2-Clause BSD License, see LICENSE file. 4 5 Authors: Luna Nielsen 6 */ 7 module engine.audio.sound; 8 import engine.audio.astream; 9 import bindbc.openal; 10 import engine.math; 11 12 /** 13 A sound 14 */ 15 class Sound { 16 private: 17 ALuint bufferId; 18 ALuint sourceId; 19 20 public: 21 ~this() { 22 alDeleteSources(1, &sourceId); 23 alDeleteBuffers(1, &bufferId); 24 } 25 26 /** 27 Construct a sound from a file path 28 */ 29 this(string file) { 30 this(open(file)); 31 } 32 33 /** 34 Construct a sound 35 */ 36 this(AudioStream stream) { 37 38 // Generate buffer 39 alGenBuffers(1, &bufferId); 40 ubyte[] data = stream.readAll(); 41 alBufferData(bufferId, stream.format, data.ptr, cast(int)data.length, cast(int)stream.bitrate/stream.channels); 42 43 // Generate source 44 alGenSources(1, &sourceId); 45 alSourcei(sourceId, AL_BUFFER, bufferId); 46 alSourcef(sourceId, AL_PITCH, 1); 47 alSourcef(sourceId, AL_GAIN, 0.5); 48 } 49 50 /** 51 Play sound 52 */ 53 void play(float gain = 0.5, float pitch = 1, vec3 position = vec3(0)) { 54 alSource3f(sourceId, AL_POSITION, position.x, position.y, position.z); 55 alSourcef(sourceId, AL_PITCH, pitch); 56 alSourcef(sourceId, AL_GAIN, gain); 57 alSourcePlay(sourceId); 58 } 59 60 void setPitch(float pitch) { 61 alSourcef(sourceId, AL_PITCH, pitch); 62 } 63 64 void setGain(float gain) { 65 alSourcef(sourceId, AL_GAIN, gain); 66 } 67 68 /** 69 Stop sound 70 */ 71 void stop() { 72 alSourceStop(sourceId); 73 } 74 }