Debian Codegraph @

examples/simple_looping.c

raw symbols SCIP
1 /*
2 Shows one way to handle looping of a sound.
3
4 This example uses a decoder as the data source. Decoders can be used with the `ma_data_source` API which, conveniently,
5 supports looping via the `ma_data_source_read_pcm_frames()` API. To use it, all you need to do is pass a pointer to the
6 decoder straight into `ma_data_source_read_pcm_frames()` and it will just work.
7 */
8 #include "../miniaudio.c"
9
10 #include <stdio.h>
11
12 void data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount)
13 {
14 ma_decoder* pDecoder = (ma_decoder*)pDevice->pUserData;
15 if (pDecoder == NULL) {
16 return;
17 }
18
19 /* Reading PCM frames will loop based on what we specified when called ma_data_source_set_looping(). */
20 ma_data_source_read_pcm_frames(pDecoder, pOutput, frameCount, NULL);
21
22 (void)pInput;
23 }
24
25 int main(int argc, char** argv)
26 {
27 ma_result result;
28 ma_decoder decoder;
29 ma_device_config deviceConfig;
30 ma_device device;
31
32 if (argc < 2) {
33 printf("No input file.\n");
34 return -1;
35 }
36
37 result = ma_decoder_init_file(argv[1], NULL, &decoder);
38 if (result != MA_SUCCESS) {
39 return -2;
40 }
41
42 /*
43 A decoder is a data source which means we just use ma_data_source_set_looping() to set the
44 looping state. We will read data using ma_data_source_read_pcm_frames() in the data callback.
45 */
46 ma_data_source_set_looping(&decoder, MA_TRUE);
47
48 deviceConfig = ma_device_config_init(ma_device_type_playback);
49 deviceConfig.playback.format = decoder.outputFormat;
50 deviceConfig.playback.channels = decoder.outputChannels;
51 deviceConfig.sampleRate = decoder.outputSampleRate;
52 deviceConfig.dataCallback = data_callback;
53 deviceConfig.pUserData = &decoder;
54
55 if (ma_device_init(NULL, &deviceConfig, &device) != MA_SUCCESS) {
56 printf("Failed to open playback device.\n");
57 ma_decoder_uninit(&decoder);
58 return -3;
59 }
60
61 if (ma_device_start(&device) != MA_SUCCESS) {
62 printf("Failed to start playback device.\n");
63 ma_device_uninit(&device);
64 ma_decoder_uninit(&decoder);
65 return -4;
66 }
67
68 printf("Press Enter to quit...");
69 getchar();
70
71 ma_device_uninit(&device);
72 ma_decoder_uninit(&decoder);
73
74 return 0;
75 }