]> git.tdb.fi Git - libs/al.git/blob - source/jukebox.cpp
Fix some uninitialized variables and memory leaks
[libs/al.git] / source / jukebox.cpp
1 /* $Id$
2
3 This file is part of libmspal
4 Copyright © 2009  Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #include <algorithm>
9 #include <cstdlib>
10 #include "jukebox.h"
11 #include "sound.h"
12
13 using namespace std;
14
15 namespace Msp {
16 namespace AL {
17
18 Jukebox::Jukebox():
19         streamer(source),
20         sound(0),
21         shuffle(false)
22 { }
23
24 Jukebox::~Jukebox()
25 {
26         streamer.stop();
27         delete sound;
28 }
29
30 void Jukebox::add_track(const string &trk)
31 {
32         bool was_empty=tracks.empty();
33         tracks.push_back(trk);
34         if(was_empty)
35                 current_track=tracks.begin();
36 }
37
38 void Jukebox::remove_track(const string &trk)
39 {
40         list<string>::iterator i=find(tracks.begin(), tracks.end(), trk);
41         if(i!=tracks.end())
42         {
43                 if(i==current_track)
44                         next();
45                 tracks.erase(i);
46         }
47 }
48
49 void Jukebox::clear_tracks()
50 {
51         stop();
52         tracks.clear();
53 }
54
55 void Jukebox::set_shuffle(bool s)
56 {
57         shuffle=s;
58 }
59
60 void Jukebox::play()
61 {
62         if(tracks.empty() || sound)
63                 return;
64
65         sound=new AL::Sound;
66         sound->open_file(*current_track);
67         streamer.play(*sound);
68 }
69
70 void Jukebox::next()
71 {
72         stop();
73         if(tracks.size()>1)
74         {
75                 if(shuffle)
76                 {
77                         while(1)
78                         {
79                                 list<string>::iterator i=tracks.begin();
80                                 advance(i, rand()%tracks.size());
81                                 if(i!=current_track)
82                                 {
83                                         current_track = i;
84                                         break;
85                                 }
86                         }
87                 }
88                 else
89                 {
90                         ++current_track;
91                         if(current_track==tracks.end())
92                                 current_track=tracks.begin();
93                 }
94         }
95         play();
96 }
97
98 void Jukebox::stop()
99 {
100         streamer.stop();
101         delete sound;
102         sound=0;
103 }
104
105 void Jukebox::tick()
106 {
107         streamer.tick();
108         if(sound && sound->eof())
109                 next();
110 }
111
112 } // namespace AL
113 } // namespace Msp