]> git.tdb.fi Git - libs/al.git/blob - source/sound.cpp
896d1d5c392798eb63595b0bb1b1f402a990a1fa
[libs/al.git] / source / sound.cpp
1 /* $Id$
2
3 This file is part of libmspal
4 Copyright © 2008 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #include <msp/core/except.h>
9 #include "sound.h"
10
11 using namespace std;
12
13 namespace Msp {
14 namespace AL {
15
16 Sound::Sound():
17         data(0)
18 {
19         ovfile.datasource=0;
20 }
21
22 Sound::~Sound()
23 {
24         if(ovfile.datasource)
25                 ov_clear(&ovfile);
26 }
27
28 void Sound::open(const string &fn)
29 {
30         if(ov_fopen(const_cast<char *>(fn.c_str()), &ovfile)<0)
31                 throw Exception("Could not open ogg vorbis file "+fn);
32
33         vorbis_info *info=ov_info(&ovfile, -1);
34         freq=info->rate;
35         switch(info->channels)
36         {
37         case 1: format=MONO16; break;
38         case 2: format=STEREO16; break;
39         default: throw Exception("Unsupported number of channels");
40         }
41 }
42
43 void Sound::load_data()
44 {
45         if(data)
46                 throw InvalidState("Data has already been loaded");
47
48         size=ov_pcm_total(&ovfile, 0)*4;
49         data=new char[size];
50         unsigned pos=0;
51         while(unsigned len=read(data+pos, size-pos))
52                 pos+=len;
53         size=pos;
54 }
55
56 void Sound::load(const string &fn)
57 {
58         open(fn);
59         load_data();
60 }
61
62 const char *Sound::get_data() const
63 {
64         if(!data)
65                 throw InvalidState("Data has not been loaded");
66         return data;
67 }
68
69 unsigned Sound::read(char *buf, unsigned len)
70 {
71         int section=0;
72         int res=ov_read(&ovfile, buf, len, 0, 2, 1, &section);
73         if(res<0)
74                 throw Exception("Error reading ogg vorbis file");
75         return res;
76 }
77
78 } // namespace AL
79 } // namespace Msp