1 /* splayMEM2.c
2  * An example on how to use libmikmod to play a module
3  * from a memory buffer using library-provided readers.
4  *
5  * (C) 2004, Raphael Assenat (raph@raphnet.net)
6  *
7  * This example is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRENTY; without event the implied warrenty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10  */
11 
12 #include <stdlib.h>
13 #include <stdio.h>
14 #include <mikmod.h>
15 
16 #if defined(_WIN32)
17 #define MikMod_Sleep(ns) Sleep(ns / 1000)
18 #elif defined(_MIKMOD_AMIGA)
19 void amiga_sysinit (void);
20 void amiga_usleep (unsigned long timeout);
21 #define MikMod_Sleep(ns) amiga_usleep(ns)
22 #else
23 #include <unistd.h>  /* for usleep() */
24 #define MikMod_Sleep(ns) usleep(ns)
25 #endif
26 
main(int argc,char ** argv)27 int main(int argc, char **argv)
28 {
29 	MODULE *module;
30 	char *data_buf;
31 	long data_len;
32 	FILE *fptr;
33 
34 	if (argc < 2) {
35 		fprintf(stderr, "Usage: ./splayMEM2 file\n");
36 		return 1;
37 	}
38 
39 #ifdef _MIKMOD_AMIGA
40 	amiga_sysinit ();
41 #endif
42 
43 	/* initialize MikMod threads */
44 	MikMod_InitThreads ();
45 
46 	/* register all the drivers */
47 	MikMod_RegisterAllDrivers();
48 
49 	/* register all the module loaders */
50 	MikMod_RegisterAllLoaders();
51 
52 	/* init the library */
53 	md_mode |= DMODE_SOFT_MUSIC | DMODE_NOISEREDUCTION;
54 	md_mode |= DMODE_HQMIXER;
55 
56 	if (MikMod_Init("")) {
57 		fprintf(stderr, "Could not initialize sound, reason: %s\n",
58 				MikMod_strerror(MikMod_errno));
59 		return 2;
60 	}
61 
62 	/* open the file */
63 	fptr = fopen(argv[1], "rb");
64 	if (fptr == NULL) {
65 		perror("fopen");
66 		MikMod_Exit();
67 		return 1;
68 	}
69 
70 	/* calculate the file size */
71 	fseek(fptr, 0, SEEK_END);
72 	data_len = ftell(fptr);
73 	fseek(fptr, 0, SEEK_SET);
74 
75 	/* allocate a buffer and load the file into it */
76 	data_buf = malloc(data_len);
77 	if (data_buf == NULL) {
78 		perror("malloc");
79 		fclose(fptr);
80 		MikMod_Exit();
81 		return 1;
82 	}
83 	if (fread(data_buf, data_len, 1, fptr) != 1)
84 	{
85 		perror("fread");
86 		fclose(fptr);
87 		free(data_buf);
88 		MikMod_Exit();
89 		return 1;
90 	}
91 	fclose(fptr);
92 
93 	/* load module */
94 	module = Player_LoadMem(data_buf, data_len, 64, 0);
95 	free(data_buf);
96 	if (module) {
97 		/* start module */
98 		printf("Playing %s\n", module->songname);
99 		Player_Start(module);
100 
101 		while (Player_Active()) {
102 			MikMod_Sleep(10000);
103 			MikMod_Update();
104 		}
105 
106 		Player_Stop();
107 		Player_Free(module);
108 	} else
109 		fprintf(stderr, "Could not load module, reason: %s\n",
110 				MikMod_strerror(MikMod_errno));
111 
112 	MikMod_Exit();
113 
114 	return 0;
115 }
116 
117