音频播放的准确(音乐级)定时 [英] Accurate (Music-grade) Timing of Audio Playback

查看:238
本文介绍了音频播放的准确(音乐级)定时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个应用程序,可以安排一些(大多数是微小的)音频文件的定时播放。抓住:它需要定时与准确的音乐。这些声音不会经常 (例如,不是例如,取样器或鼓组),但是它们将需要被绝对精确地放置。这个问题有两部分:


  1. 如何组织时间安排?我听说 NSTimer 不准确,或至少不可靠?我应该使用MIDI某种方式吗?


  2. 一旦我设置好时间,我知道什么时候播放我的声音...我应该怎么玩? 足够快速可靠,足以维持所需的准确度? NSTimer对于大多数目的来说都是足够准确的,只要你不会在任何线程上调度定时器足够长的定时器迟到。您需要及时返回到运行循环,以便下次启动日期。幸运的是,NSSound异步播放,所以这不应该是一个问题。



    通常导致NSTimers问题的是当人们设置间隔真的很低它在1厘秒)。如果你做的时间比这个时间间隔(和花费超过1厘秒是很容易),那么你会回到运行循环,在定时器应该启动,这将使定时器迟到,这将拧紧你的时间。



    你只需要尽可能快地实现你的计时器方法,如果你不能使它足够快,使一个NSOperation子类来做这项工作,让你的定时器方法实例化操作,设置它,并将它添加到操作队列。 (操作将在另一个线程上运行,所以它不会占用您的计时器的运行循环的线程。)如果计时器可能真的频繁,那么这是一个微优化(由仪器和鲨鱼,当然)可能有保证。


    I'm attempting to write an app that can arrange timed playback of some (mostly tiny) audio files. The catch: it needs to be timed with accuracy worthy of music. The sounds won't be played frequently (it's not, for example, a sampler or a drum kit), but they will need to be absolutely precisely placed. There are two parts to this question:

    1. How should I organize the timing? I've heard NSTimer is inaccurate, or at least unreliable? Should I use MIDI somehow? Or a tight loop and some time-getting function with high resolution?

    2. Once I've got the timing set up, and I know when to play my sounds... how should I play them? Is NSSound fast and reliable enough to maintain the accuracy needed?

    解决方案

    NSTimer is accurate enough for most purposes as long as you don't dilly-dally on whatever thread the timer is scheduled on long enough for the timer to be late. You need to return to the run loop in time for its next fire date. Fortunately, NSSound plays asynchronously, so this shouldn't be a problem.

    What usually causes problems with NSTimers is when people set the interval really low (one question I saw had it at 1 centisecond). If what you do takes longer than that interval (and taking longer than 1 centisecond is really easy), then you will return to the run loop after the timer was supposed to fire, which will make the timer late, which will screw up your timing.

    You just need to make your timer method implementation as fast as possible, and if you can't make it fast enough, make an NSOperation subclass to do the job and have your timer method just instantiate the operation, set it up, and add it to an operation queue. (The operation will run on another thread, so it won't tie up the thread whose run loop you scheduled your timer on.) If the timer may be really frequent, then this is one case where micro-optimization (guided by Instruments and Shark, of course) may be warranted.

    这篇关于音频播放的准确(音乐级)定时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆