source: trunk/src/sample.cpp @ 2492

Last change on this file since 2492 was 2492, checked in by sam, 10 years ago

audio: add a simple Stop() method to samples.

  • Property svn:keywords set to Id
File size: 2.1 KB
Line 
1//
2// Lol Engine
3//
4// Copyright: (c) 2010-2013 Sam Hocevar <sam@hocevar.net>
5//   This program is free software; you can redistribute it and/or
6//   modify it under the terms of the Do What The Fuck You Want To
7//   Public License, Version 2, as published by Sam Hocevar. See
8//   http://www.wtfpl.net/ for more details.
9//
10
11#if defined HAVE_CONFIG_H
12#   include "config.h"
13#endif
14
15#include <cstdlib>
16#include <cstdio>
17#include <cstring>
18
19#if defined USE_SDL_MIXER
20#   if defined HAVE_SDL_SDL_H
21#      include <SDL/SDL.h>
22#   else
23#      include <SDL.h>
24#   endif
25#   if defined HAVE_SDL_SDL_MIXER_H
26#      include <SDL/SDL_mixer.h>
27#   else
28#      include <SDL_mixer.h>
29#   endif
30#endif
31
32#include "core.h"
33
34using namespace std;
35
36namespace lol
37{
38
39/*
40 * Sample implementation class
41 */
42
43class SampleData
44{
45    friend class Sample;
46
47private:
48    char *name, *path;
49#if defined USE_SDL_MIXER
50    Mix_Chunk *m_chunk;
51    int m_channel;
52#endif
53};
54
55/*
56 * Public Sample class
57 */
58
59Sample::Sample(char const *path)
60  : data(new SampleData())
61{
62    data->name = (char *)malloc(9 + strlen(path) + 1);
63    data->path = data->name + 9;
64    sprintf(data->name, "<sample> %s", path);
65
66#if defined USE_SDL_MIXER
67    Array<String> pathlist = System::GetPathList(path);
68    for (int i = 0; i < pathlist.Count(); ++i)
69    {
70        data->m_chunk = Mix_LoadWAV(pathlist[i].C());
71        if (data->m_chunk)
72            break;
73    }
74    if (!data->m_chunk)
75    {
76#if !LOL_RELEASE
77        Log::Error("could not load sample %s\n", path);
78#endif
79        SDL_Quit();
80        exit(1);
81    }
82    data->m_channel = -1;
83#endif
84}
85
86Sample::~Sample()
87{
88#if defined USE_SDL_MIXER
89    Mix_FreeChunk(data->m_chunk);
90#endif
91    free(data->name);
92    delete data;
93}
94
95void Sample::TickGame(float seconds)
96{
97    Entity::TickGame(seconds);
98}
99
100char const *Sample::GetName()
101{
102    return data->name;
103}
104
105void Sample::Play()
106{
107#if defined USE_SDL_MIXER
108    data->m_channel = Mix_PlayChannel(-1, data->m_chunk, 0);
109#endif
110}
111
112void Sample::Stop()
113{
114#if defined USE_SDL_MIXER
115    if (data->m_channel >= 0)
116        Mix_HaltChannel(data->m_channel);
117    data->m_channel = -1;
118#endif
119}
120
121} /* namespace lol */
122
Note: See TracBrowser for help on using the repository browser.