Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to find musical key of a given sample? #369

Open
apoorv569 opened this issue Jul 23, 2022 · 0 comments
Open

How to find musical key of a given sample? #369

apoorv569 opened this issue Jul 23, 2022 · 0 comments

Comments

@apoorv569
Copy link

I am trying to implement key detection for a application that I am developing. Basically I want the key as in "A" "A#" "C" "F#" etc, but I will do the freq to key conversion later. I am using aubio_pitch but it is not working as intended.

    float cUtils::GetMusicalKey(const std::string& path)
    {
        uint_t buff_size = 1024, hop_size = buff_size / 4, frames = 0, samplerate = 0, read = 0;
        aubio_pitch_t* pitch;
        fvec_t* in, *out;
        aubio_source_t* source = new_aubio_source(path.c_str(), samplerate, hop_size);

        float key = 0.0f;

        if (!source)
            return 0.0f;
        else
        {
            try
            {
                if (samplerate == 0)
                    samplerate = aubio_source_get_samplerate(source);

                pitch = new_aubio_pitch("default", buff_size, hop_size, samplerate);

                if (!pitch)
                    return 0.0f;

                in = new_fvec(hop_size);
                out = new_fvec(1);

                do
                {
                    aubio_source_do(source, in, &read);
                    aubio_pitch_do(pitch, in, out);

                    frames ++;

                    key = fvec_get_sample(out, 0);
                }
                while (read == hop_size);

                if (new_aubio_pitch("default", buff_size, hop_size, samplerate))
                {
                    SH_LOG_DEBUG("Track: {}, with confidence: {}, silence: {}, tolerance: {} key: {}",
                                 path, aubio_pitch_get_confidence(pitch), aubio_pitch_get_silence(pitch), aubio_pitch_get_tolerance(pitch), key);
                }

                if (aubio_pitch_set_unit(pitch, "Hz"))
                    SH_LOG_DEBUG("Pitch unit set to Hz");

                // Clean up memory
                del_aubio_pitch(pitch);
                del_fvec(out);
                del_fvec(in);
                del_aubio_source(source);
                aubio_cleanup();
            }
            catch (std::exception& e)
            {
                SH_LOG_ERROR("Aubio Error! {}", e.what());
            }
        }

        return key;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant