【问题标题】:AVAudioPlayer doesn't work in shared class swiftAVAudioPlayer 在共享类 swift 中不起作用
【发布时间】:2015-12-10 09:39:01
【问题描述】:

我从一个单例类中调用一个方法,该方法允许播放来自其他类的声音但播放器不起作用,我尝试了处理相同问题的帖子中提到的方法,但它对我不起作用,在这里是我的代码:

import Foundation
import AVFoundation
import UIKit
var soundPlayer = AVAudioPlayer()

class MySingleton: NSObject, AVAudioPlayerDelegate {
var timer = NSTimer()

   class var sharedSingleton: MySingleton {
    struct Static {
        static var onceTocken: dispatch_once_t = 0
        static var instance : MySingleton? = nil
    }
    dispatch_once(&Static.onceTocken) {
        Static.instance = MySingleton()
    }
    return Static.instance!
        }
func callTimer () {
    timer = NSTimer.scheduledTimerWithTimeInterval(0.6, target: self, selector: "repeatedSound", userInfo: nil, repeats: true)
}
func repeatedSound() {

    var repeatedSoundUrl = NSURL(fileURLWithPath:    NSBundle.mainBundle().pathForResource(prayerRepitationList[selectedCellInIndex], ofType: "mp3")!)

    soundPlayer = AVAudioPlayer(contentsOfURL: repeatedSoundUrl, error: nil)
    println("repeated url is \(repeatedSoundUrl)")
    soundPlayer.prepareToPlay()
    soundPlayer.delegate = self
    soundPlayer.play()


}
}

我尝试了var player : AVAudioPlayer! = nil : AVAudioPlayer! = nil 但没有工作, 我该如何解决?

【问题讨论】:

    标签: ios swift avaudioplayer


    【解决方案1】:

    创建计时器时,您需要在选择器名称的末尾添加一个冒号“:”,因为该方法指定了一个参数。它看起来像这样:

    timer = NSTimer.scheduledTimerWithTimeInterval(0.6, target: self, selector: "repeatedSound:", userInfo: nil, repeats: true)
    

    }

    而且,由于定时器调用的方法接收定时器本身的参数,所以必须这样指定:

    func repeatedSound(timer: NSTimer) {
      // your other code goes here
    }
    

    我没有尝试您的代码,但这应该会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2022-06-25
      • 1970-01-01
      相关资源
      最近更新 更多