You need to enable JavaScript to run this app.
导航
【OC】流式节拍检测
最近更新时间:2023.03.16 11:40:14首次发布时间:2023.03.16 11:40:14
实现

1.创建handle

// create SAMICore
int result = 0;

SAMICore_CreateParameter *create_param = [[SAMICore_CreateParameter alloc] init];
create_param.sampleRate = sample_rate;
create_param.maxBlockSize = pre_define_block_size;
create_param.modelBuffer = reinterpret_cast<char*>(modelBin.data());
create_param.modelLen = modelBin.size();
create_param.numChannel = num_channels;

SAMICore *sami_core_handle = [[SAMICore alloc] initWithIdentify:SAMICore_Identify_Extractor_BeatTracking param:create_param result:&result];
if(result != SAMI_OK) {
    std::cerr << "create handler failed: " << result;
    exit(-1);
}

2.初始化buffer

SAMICore_AudioBuffer *in_audio_buffer 
    = [[SAMICore_AudioBuffer alloc] initWithNumberSamples:sample_rate
                                           numberChannels:num_channels
                                             isInterleave:false];
                                             
SAMICore_AudioBlock *in_block = [[SAMICore_AudioBlock alloc] init];
in_block.dataType = SAMICore_DataType_AudioBuffer;
in_block.numberAudioData = 1;
in_block.audioData = in_audio_buffer;

3.处理数据与获取结果

for(int inx = 0; inx + pre_define_block_size < (int)num_frames;) {
    // build in_block
    for(auto c = 0; c < num_channels; ++c) {
        std::copy_n(in_samples[c].data() + inx, pre_define_block_size, ((float**)in_audio_buffer.data)[c]);
    }

    result = [sami_core_handle processWithInBlock:in_block outBlock:nil];

    if(result != SAMI_OK) {
        std::cerr << "process error: " << result;
        exit(-1);
    }

    SAMICore_Property *samiCoreProperty = [[SAMICore_Property alloc] init];
    result = [sami_core_handle getProperty:samiCoreProperty withId:SAMICore_PropertyId_FrameFeatures];

    if(result == SAMI_OK  && samiCoreProperty.data != nil) {
        if (samiCoreProperty.type == SAMICore_DataType_FeatureSet) {
            SAMICore_FeatureSet *dstSet = (SAMICore_FeatureSet*)samiCoreProperty.data;
            NSArray *set = dstSet.set;
            for(int i = 0; i < dstSet.numFeatureTypes; ++i) {
                SAMICore_FeatureArray* featureArray = [dstSet.set objectAtIndex:i];
                if(featureArray.featureID == SAMICore_PropertyId_FrameFeature_BEAT_TRACKING) {
                    SAMICore_Feature* feature = [featureArray.array objectAtIndex:0];
                    float timestamp  = feature.time;
                    float beat = feature.values[0];
                    printf("timestamp: %f; beat: %f\n", timestamp, beat);
                }

            }
            dstSet.set = [set copy];
            samiCoreProperty.data = dstSet;
        }
    }
    samiCoreProperty = nil;
    inx += pre_define_block_size;
}

4.释放handle

sami_core_handle = nil;