~aleteoryx/muditaos

ref: 70126e07acf51ca04c936c4c57d6b430001c5fe9 muditaos/module-audio/Audio/decoder/decoderWAV.cpp -rw-r--r-- 2.0 KiB
70126e07 — jimmorrisson [EGD-4439] New filesystem handling - module audio. (#1037) 5 years ago
                                                                                
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
// Copyright (c) 2017-2020, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "decoderWAV.hpp"

namespace audio
{

    decoderWAV::decoderWAV(const char *fileName) : decoder(fileName)
    {

        if (fileSize == 0) {
            return;
        }

        if (fd == NULL) {
            return;
        }

        if (std::fread(&waveHeader, 1, sizeof(waveHeader), fd) != sizeof(WAVE_FormatTypeDef)) {
            return;
        }

        // TODO:M.P; implement support for sample size different than 16bit
        // pcmsamplesbuffer.reserve(1024);

        sampleRate    = waveHeader.SampleRate;
        bitsPerSample = waveHeader.BitPerSample;
        chanNumber    = waveHeader.NbrChannels;

        isInitialized = true;
    }

    uint32_t decoderWAV::decode(uint32_t samplesToRead, int16_t *pcmData)
    {
        uint32_t samples_read = 0;

        /* TODO:M.P; implement support for sample size different than 16bit
            if(samplesToRead > pcmsamplesbuffer.max_size()){
                pcmsamplesbuffer.resize(samplesToRead);
            }*/

        switch (bitsPerSample) {
        case 8:
            // TODO:M.P not supported
            break;

        case 16:
            samples_read = std::fread(pcmData, sizeof(int16_t), samplesToRead, fd);
            break;

        case 24:
            // TODO:M.P not supported
            break;

        case 32:
            // TODO:M.P not supported
            break;
        }

        if (samples_read) {
            /* Calculate frame duration in seconds */
            position +=
                (float)((float)(chanNumber == 2 ? samplesToRead / chanNumber : samplesToRead) / (float)(sampleRate));
        }

        return samples_read;
    }

    void decoderWAV::setPosition(float pos)
    {

        std::fseek(fd, (fileSize * pos) + sizeof(WAVE_FormatTypeDef), SEEK_SET);
        // Calculate new position
        position = (float)((float)(std::ftell(fd) / sizeof(int16_t) / chanNumber) / (float)(sampleRate));
    }

} // namespace audio