Swift Sound重播

时间:2014-12-07 10:46:37

标签: ios swift sprite-kit

我有这个功能,我在第一个场景中生活:

    func ThemeSound() {
        if let path = NSBundle.mainBundle().pathForResource("InfinityThemeMain", ofType: "wav") {
            let enemy1sound = NSURL(fileURLWithPath:path)
            println(enemy1sound)

            var error:NSError?
            ThemePlayer = AVAudioPlayer(contentsOfURL: enemy1sound, error: &error)
            ThemePlayer.prepareToPlay()
            ThemePlayer.play()
        }
    }

但问题是,它只播放一次主题。我需要它重复播放。我以为我知道如何实现这一目标。

runAction(SKAction.repeatActionForever(SKAction.sequence([SKAction.runBlock(ThemePlayer), SKAction.waitForDuration(2.55)]))

但是我不能粘贴在ViewController中,因为runAction需要一个子连接它。 我能用其他任何方式吗?

2 个答案:

答案 0 :(得分:35)

只需将numberOfLoops属性设置为负数即可。

ThemePlayer.numberOfLoops = -1

来自the documentation

  

numberOfLoops   到达结尾时声音将返回到开头的次数,以重复播放。

     

...

     

var numberOfLoops:Int

     

...

     

值为0(默认值)表示播放一次声音。设置正整数值以指定返回到开始并再次播放的次数。例如,指定值1会导致声音的总共两次播放。 设置任何负整数值以无限循环播放声音,直到您调用stop方法

您可能还需要make your AVAudioPlayer a property, rather than a local variable。通过自动引用计数,我认为您的本地ThemePlayer实例可能会被ARC取消分配。比我更了解AVAudioPlayer的人可能会对此发表评论。

(顺便说一下,您可能希望遵循Apple的命名对象实例的惯例,以小写字母开头,例如themePlayer而不是ThemePlayer。这将使您的代码更容易让其他人使用读出。)

答案 1 :(得分:0)

我使用Timer()重复它 这是我的代码:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var player = AVAudioPlayer()

    var timer = Timer()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



    @IBAction func play(_ sender: UIButton) {

       // var player = AVAudioPlayer()


        let soundURL = Bundle.main.url(forResource: "beeb", withExtension: "wav")

        do {
            player = try AVAudioPlayer(contentsOf: soundURL!)
        } catch {
            print("No sound found by URL")
        }



        alertation(title: "click stop to stop", msg: "")


    }


    func alertation(title:String,msg:String)
    {

        player.play()
        self.timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true, block: { (timer) in
            self.player.play()
        })



        var alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
        var stop = alert.addAction(UIAlertAction(title: "STOP", style: .default, handler: { (action) in

             self.player.stop()
            self.timer.invalidate()

        }))


        self.present(alert, animated: true, completion: nil)

    }



}