iphone - 简单的节拍器

标签 iphone objective-c ios grand-central-dispatch

我正在尝试通过每0.25秒播放一次系统声音来编写一个简单的节拍器。我使用GCD在单独的线程上播放点击,但是播放不均匀,点击有时是两次快速拍打,然后是较慢的拍打。我记录了执行循环中的if语句的时间以及它在0.25秒时的正确时间。我希望我不必使用音频队列服务。有什么建议么?

- (IBAction)start:(id)sender 
{
    dispatch_queue_t clickQueue; // the queue to run the metronome clicker
    dispatch_queue_t mainQueue; // I access the main queue to demonstrate how to change UIKit items
    //clickQueue = dispatch_queue_create("clickQueue", NULL);
    clickQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    mainQueue = dispatch_get_main_queue();
    dispatch_async(clickQueue, ^{
        double timeWas = [NSDate timeIntervalSinceReferenceDate];
        //delay by a 1/10 of a second so the first few clicks don't bunch up.
        double timeIs = [NSDate timeIntervalSinceReferenceDate]  - 0.1; 
        // playing starts out as NO because it gets switched at the end of the loop
        // and the PlaySystemSound block isn't off the queue yet. There is probably a
        // better way to do this.
        while (playing) {
            timeIs = [NSDate timeIntervalSinceReferenceDate] ;
            if ((timeIs - timeWas) > (60.0/240)) {
                AudioServicesPlaySystemSound(sound);
                timeWas = timeIs;
                // I want to flast the 200 label between orange and black but I have to access
                // user interface objects from the queue that they are running in, usually the
                // main queue.
                dispatch_async(mainQueue, ^{
                    if (flash)
                        [bpm setTextColor:[UIColor orangeColor]];
                    else
                        [bpm setTextColor:[UIColor blackColor]];
                    flash = !flash;
                });
            }
        }
    });
    playing = !playing;
    if (playing) 
        [startButton setTitle:@"Stop" forState:UIControlStateNormal];
    else
        [startButton setTitle:@"Start" forState:UIControlStateNormal];
}

最佳答案

时间使用NSTimer,声音使用AVFoundation。

关于iphone - 简单的节拍器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7444652/

相关文章:

iphone - 如何禁用 iPhone 相机的自动闪光功能?

iPhone 的页面控制错误

iphone - 使用 iPhone 的蜡笔效果

iphone - 为什么 NSIndexPath 不起作用?

ios - NSUserDefault 中的 NSMutableArray,检索 NULL

ios - 带+号的界面语法(UIView+AdditionalFeatures.h)?

iphone - 使用 xcode 发布 jaiku

objective-c - 是否可以将 Swift 类转换为 C void* 指针?

ios - 蓝牙设备如何显示来自 iPhone 的来电?

ios - 当使用 swift3.0 执行按钮操作时,如何在 ios 移动设备中打开文档文件,例如(.pdf、.doc、.docx)?