井原プロダクトのBLOG

Since 2013。個人でアプリ作っています。

Smart Metronome TAPテンポ検出のプログラム

Smart Metornomedでは、6回のタップの平均間隔を計算してテンポ設定しています。以下ソースコード

//
//  ViewController.m
//  tapTempo
//
//  Created by Tomohiro Ihara on 2019/07/20.
//  Copyright © 2019 Tomohiro Ihara. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *myLabel;

@end

@implementation ViewController

NSDate *taptimeSave;  //最後にtapされた時間を保存
NSMutableArray *tapsave; //tap間隔を保存
NSInteger tapCounter, tapdataCounter;

- (void)viewDidLoad {
    [super viewDidLoad];
    taptimeSave = [NSDate date];
    tapCounter = 0;
    tapdataCounter = 0;
    tapsave = [NSMutableArray array];
    for (int i=0; i<6; i++) {
        [tapsave addObject:@"0"];
    }
}


- (IBAction)tap:(UIButton *)sender {
    //**********  タップしたテンポを表示する
    float x, ave;
    NSDate *now = [NSDate date];
    x = [now timeIntervalSinceDate:taptimeSave];
    taptimeSave = now;
    //前回のTAPから3秒以上経っていたら最初から計測
    if (x < 3) {
        [tapsave replaceObjectAtIndex:tapCounter withObject:[NSString stringWithFormat:@"%f",x]];
        //平均値を求める(値が0は除く)
        float sum  = 0;
        tapdataCounter = 0;
        for (int i=0; i< tapsave.count; i++) {
            if ([tapsave[i] floatValue] > 0) {
                sum += [tapsave[i] floatValue];
                tapdataCounter ++;
            }
        }
        if (tapdataCounter > 0){
            ave = 60/sum  * tapdataCounter;
            NSLog (@"ave:%f", ave);
            NSLog (@"sum:%f", sum);

            //最大値最小値補正
            if (ave > 999) {
                ave = 999;
            }
            if (ave < 1){
                ave = 1;
            }
            //カウンター更新
            tapCounter++;
            if (tapCounter > tapsave.count-1){
                tapCounter = 0;
            }
            _myLabel.text = [NSString stringWithFormat:@"%ld",(long)ave];
        }
    } else {
        //最初なので全部クリア
        for (int i=0; i< tapsave.count; i++) {
            tapsave[i] = @"0";
        }
    }
}

@end