forked from CurryGuy/ndsp-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
135 lines (104 loc) · 2.38 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <3ds.h>
#include <cstdlib>
#include <cstring>
#include <cstdio>
int main(int argc, char* argv[])
{
gfxInitDefault();
consoleInit(GFX_TOP, nullptr);
// The dsp channel number
constexpr int channel = 1;
u32 sampleRate;
u32 dataSize;
u16 channels;
u16 bitsPerSample;
// Initialize ndsp
ndspInit();
ndspSetOutputMode(NDSP_OUTPUT_STEREO);
ndspSetOutputCount(1); // Num of buffers
// Reading wav file
FILE* fp = fopen("./example.wav", "rb");
if(!fp)
{
printf("Could not open the example.wav file.\n");
return 1;
}
char signature[4];
fread(signature, 1, 4, fp);
if( signature[0] != 'R' &&
signature[1] != 'I' &&
signature[2] != 'F' &&
signature[3] != 'F')
{
printf("Wrong file format.\n");
fclose(fp);
return 1;
}
fseek(fp,0,SEEK_END);
dataSize = ftell(fp);
fseek(fp, 22, SEEK_SET);
fread(&channels, 2, 1, fp);
fseek(fp, 24, SEEK_SET);
fread(&sampleRate, 4, 1, fp);
fseek(fp, 34, SEEK_SET);
fread(&bitsPerSample, 2, 1, fp);
if(dataSize == 0 || (channels != 1 && channels != 2) ||
(bitsPerSample != 8 && bitsPerSample != 16))
{
printf("Corrupted wav file.\n");
fclose(fp);
return 1;
}
// Allocating and reading samples
u8* data = static_cast<u8*>(linearAlloc(dataSize));
if(!data)
{
fclose(fp);
return 1;
}
fseek(fp, 44, SEEK_SET);
fread(data, 1, dataSize, fp);
fclose(fp);
// Find the right format
u16 ndspFormat;
if(bitsPerSample == 8)
{
ndspFormat = (channels == 1) ?
NDSP_FORMAT_MONO_PCM8 :
NDSP_FORMAT_STEREO_PCM8;
}
else
{
ndspFormat = (channels == 1) ?
NDSP_FORMAT_MONO_PCM16 :
NDSP_FORMAT_STEREO_PCM16;
}
ndspChnReset(channel);
ndspChnSetInterp(channel, NDSP_INTERP_NONE);
ndspChnSetRate(channel, float(sampleRate));
ndspChnSetFormat(channel, ndspFormat);
// Create and play a wav buffer
ndspWaveBuf waveBuf;
std::memset(&waveBuf, 0, sizeof(ndspWaveBuf));
waveBuf.data_vaddr = (const void*)data;
waveBuf.nsamples = dataSize / (bitsPerSample >> 3);
waveBuf.looping = true; // Loop enabled
waveBuf.status = NDSP_WBUF_FREE;
DSP_FlushDataCache(data, dataSize);
ndspChnWaveBufAdd(channel, &waveBuf);
while(aptMainLoop())
{
hidScanInput();
u32 keys = hidKeysDown();
if(keys & KEY_START)
break;
gfxFlushBuffers();
gfxSwapBuffers();
gspWaitForVBlank();
}
ndspChnWaveBufClear(channel);
linearFree(data);
gfxExit();
ndspExit();
return 0;
}