comparison src/libmlk-core/core/music.c @ 320:8f9937403749

misc: improve loading of data
author David Demelier <markand@malikania.fr>
date Fri, 01 Oct 2021 20:30:00 +0200
parents libmlk-core/core/music.c@d01e83210ca2
children 0c18acf4517e
comparison
equal deleted inserted replaced
319:b843eef4cc35 320:8f9937403749
1 /*
2 * music.h -- music support
3 *
4 * Copyright (c) 2020-2021 David Demelier <markand@malikania.fr>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19 #include <assert.h>
20 #include <string.h>
21
22 #include <SDL_mixer.h>
23
24 #include "error.h"
25 #include "music.h"
26
27 int
28 music_open(struct music *mus, const char *path)
29 {
30 assert(mus);
31 assert(path);
32
33 if (!(mus->handle = Mix_LoadMUS(path)))
34 return errorf("%s", SDL_GetError());
35
36 return 0;
37 }
38
39 int
40 music_openmem(struct music *mus, const void *buffer, size_t buffersz)
41 {
42 assert(mus);
43 assert(buffer);
44
45 SDL_RWops *ops;
46
47 if (!(ops = SDL_RWFromConstMem(buffer, buffersz)) ||
48 !(mus->handle = Mix_LoadMUS_RW(ops, 1)))
49 return errorf("%s", SDL_GetError());
50
51 return 0;
52 }
53
54 int
55 music_ok(const struct music *mus)
56 {
57 return mus && mus->handle;
58 }
59
60 int
61 music_play(struct music *mus, enum music_flags flags, unsigned int fadein)
62 {
63 assert(mus);
64
65 int loops = flags & MUSIC_LOOP ? -1 : 1;
66 int ret;
67
68 if (fadein > 0)
69 ret = Mix_FadeInMusic(mus->handle, loops, fadein);
70 else
71 ret = Mix_PlayMusic(mus->handle, loops);
72
73 if (ret < 0)
74 return errorf("%s", SDL_GetError());
75
76 return 0;
77 }
78
79 int
80 music_playing(void)
81 {
82 return Mix_PlayingMusic();
83 }
84
85 void
86 music_pause(void)
87 {
88 Mix_PauseMusic();
89 }
90
91 void
92 music_resume(void)
93 {
94 Mix_ResumeMusic();
95 }
96
97 void
98 music_stop(unsigned int fadeout)
99 {
100 if (fadeout > 0)
101 Mix_FadeOutMusic(fadeout);
102 else
103 Mix_HaltMusic();
104 }
105
106 void
107 music_finish(struct music *mus)
108 {
109 assert(mus);
110
111 if (mus->handle) {
112 Mix_HaltMusic();
113 Mix_FreeMusic(mus->handle);
114 }
115
116 memset(mus, 0, sizeof (*mus));
117 }