【问题标题】:How to activate a function after a given time? [closed]如何在给定时间后激活功能? [关闭]
【发布时间】:2016-04-24 13:28:59
【问题描述】:

我想在播放完声音后激活一个功能。我假设需要包含 NSTimer,但我不确定如何实现它。如果您能给我一些有效的代码,那将很有帮助。

【问题讨论】:

  • 你试过用谷歌搜索你的问题吗?例如,swift nstimer 给出了很多结果。

标签: ios swift audio nstimer


【解决方案1】:

您应该发布您尝试过的代码,然后有人可以帮助您使代码正常工作。在这种情况下,您不需要为您正在做的事情设置计时器。播放器上的AVAudioPlayerDelegate 协议专为您尝试做的事情而设计:

import UIKit
import AVFoundation

class ViewController: UIViewController, AVAudioPlayerDelegate {

    var audioPlayer:AVAudioPlayer?

    func playSound(fileName:NSString)
    {
        let path = NSBundle.mainBundle().pathForResource(fileName, ofType:"wav")
        let url = NSURL.fileURLWithPath(path!)

        do {
            try audioPlayer = AVAudioPlayer(contentsOfURL: url)
            audioPlayer?.delegate = self
            audioPlayer?.play()
        } catch {
            print("Player not available")
        }
    }

    //MARK : AVAudioPlayerDelegate
    func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
        print("finished playing, do something else here")
    }
}

【讨论】:

  • 这也是我推荐的。 AVAudioPlayerDelegate audioPlayerDidFinishPlaying(_, successfully:) 方法是在声音播放完毕时调用代码的方式。
猜你喜欢
  • 1970-01-01
  • 2017-06-14
  • 1970-01-01
  • 2018-09-11
  • 2014-02-09
  • 2011-02-03
  • 2013-06-18
  • 2017-01-19
  • 1970-01-01
相关资源
最近更新 更多