//
// Created by Gloomy on 2017/6/30.
//

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "org_fmod_example_MainActivity.h"
#include "fmod.hpp"
#include "fmod_dsp_effects.h"

using namespace FMOD;

JNIEXPORT void JNICALL Java_org_fmod_example_MainActivity_playSound
        (JNIEnv *env, jclass jcls, jstring filename_jstr, jint type) {
    const char *filename = env->GetStringUTFChars(filename_jstr, NULL);
    System *system;
    Sound *sound;
    Channel *channel;
    DSP *dsp;
    bool isPlaying = true;


    System_Create(&system);
    system->init(32, FMOD_INIT_NORMAL, NULL);

    char *filePath = (char *) calloc(256, sizeof(char));
    strcat(filePath, "file:///android_asset/");
    strcat(filePath, filename);

    try {
        system->createSound(filePath, FMOD_DEFAULT, 0, &sound);
        system->playSound(sound, 0, false, &channel);
        switch (type) {
            case 0://正常
                break;
            case 1://萝莉
                system->createDSPByType(FMOD_DSP_TYPE_PITCHSHIFT, &dsp); //萝莉
                dsp->setParameterFloat(FMOD_DSP_PITCHSHIFT_PITCH, 2.5f);
                channel->addDSP(0, dsp);
                break;
            case 2://大叔
                system->createDSPByType(FMOD_DSP_TYPE_PITCHSHIFT, &dsp);
                dsp->setParameterFloat(FMOD_DSP_PITCHSHIFT_PITCH, 0.8f);
                channel->addDSP(0, dsp);
                break;
            case 3://搞怪
                float frequency;
                channel->getFrequency(&frequency);
                frequency *= 2.0f;
                channel->setFrequency(frequency);
                break;
            case 4: //空灵
                system->createDSPByType(FMOD_DSP_TYPE_ECHO, &dsp);
                dsp->setParameterFloat(FMOD_DSP_ECHO_DELAY, 300);
                dsp->setParameterFloat(FMOD_DSP_ECHO_FEEDBACK, 20);
                channel->addDSP(0, dsp);
                break;
            case 5://惊悚
                system->createDSPByType(FMOD_DSP_TYPE_TREMOLO, &dsp);
                dsp->setParameterFloat(FMOD_DSP_TREMOLO_SKEW, 0.5f);
                channel->addDSP(0, dsp);
                break;
        }
    } catch (...) {
        goto end;
    }

    system->update();
    do {
        channel->isPlaying(&isPlaying);
        usleep(1000 * 1000);
    } while (isPlaying);

    end:
    free(filePath);
    sound->release();
    system->close();
    system->release();

    env->ReleaseStringUTFChars(filename_jstr, filename);
}
