我有这样的功能,我在第一个场景中赋予了生命:
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需要一个子级来附加它。还有别的办法吗?
发布于 2014-12-07 19:35:43
只需将numberOfLoops属性设置为负数。
ThemePlayer.numberOfLoops = -1numberOfLoops声音在到达结尾时返回到开头重复播放的次数。
..。
var numberOfLoops:整型
..。
默认值为0,表示播放一次声音。设置一个正整数值以指定返回到开始并再次播放的次数。例如,指定值1将导致声音总共播放两次。设置任何负整数值以无限期循环声音,直到您调用方法为止。
您可能还需要make your AVAudioPlayer a property, rather than a local variable。现在,通过自动引用计数,我认为你的本地ThemePlayer实例很可能会被ARC释放。比我更了解AVAudioPlayer的人可能会对此发表评论。
(顺便说一句,你可能想要遵循苹果的惯例,以小写字母开头命名对象实例,例如themePlayer而不是ThemePlayer。这将使其他人更容易阅读您的代码。)
发布于 2016-12-08 03:03:23
下面是我的代码,我使用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)
}
}https://stackoverflow.com/questions/27341835
复制相似问题