]> git.tdb.fi Git - libs/al.git/blobdiff - source/sound.cpp
Initial revision
[libs/al.git] / source / sound.cpp
diff --git a/source/sound.cpp b/source/sound.cpp
new file mode 100644 (file)
index 0000000..bc4db1e
--- /dev/null
@@ -0,0 +1,79 @@
+/* $Id$
+
+This file is part of libmspal
+Copyright © 2008 Mikko Rasa, Mikkosoft Productions
+Diestributed under the LGPL
+*/
+
+#include <msp/core/except.h>
+#include "sound.h"
+
+using namespace std;
+
+namespace Msp {
+namespace AL {
+
+Sound::Sound():
+       data(0)
+{
+       ovfile.datasource=0;
+}
+
+Sound::~Sound()
+{
+       if(ovfile.datasource)
+               ov_clear(&ovfile);
+}
+
+void Sound::open(const string &fn)
+{
+       if(ov_fopen(const_cast<char *>(fn.c_str()), &ovfile)<0)
+               throw Exception("Could not open ogg vorbis file");
+
+       vorbis_info *info=ov_info(&ovfile, -1);
+       freq=info->rate;
+       switch(info->channels)
+       {
+       case 1: format=MONO16; break;
+       case 2: format=STEREO16; break;
+       default: throw Exception("Unsupported number of channels");
+       }
+}
+
+void Sound::load_data()
+{
+       if(data)
+               throw InvalidState("Data has already been loaded");
+
+       size=ov_pcm_total(&ovfile, 0)*4;
+       data=new char[size];
+       unsigned pos=0;
+       while(unsigned len=read(data+pos, size-pos))
+               pos+=len;
+       size=pos;
+}
+
+void Sound::load(const string &fn)
+{
+       open(fn);
+       load_data();
+}
+
+const char *Sound::get_data() const
+{
+       if(!data)
+               throw InvalidState("Data has not been loaded");
+       return data;
+}
+
+unsigned Sound::read(char *buf, unsigned len)
+{
+       int section=0;
+       int res=ov_read(&ovfile, buf, len, 0, 2, 1, &section);
+       if(res<0)
+               throw Exception("Error reading ogg vorbis file");
+       return res;
+}
+
+} // namespace AL
+} // namespace Msp