我曾经为了起到隔音下面创建一个对象类AVAudioPlayer的:
class MusicAudio: NSObject, AVAudioPlayerDelegate {
var bassAudio : AVAudioPlayer! = AVAudioPlayer()
override init() {
super.init()
let bassAudioPath = NSBundle.mainBundle().pathForResource("Raw", ofType:"mp3")
let fileURL = NSURL(fileURLWithPath: bassAudioPath!)
bassAudio = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
bassAudio.currentTime = 0
bassAudio.volume = 1.0
bassAudio.delegate = self
}
func adjustAudioLayerState(volumeOn:Bool, layer:AudioLayerState) {
if layer == AudioLayerState.Bass {
self.bassAudio.prepareToPlay()
self.bassAudio.play()
}
}
}
要播放噪音,我通过调用类:
@IBAction func testSound() {
var sound:MusicAudio = MusicAudio()
sound.adjustAudioLayerState(true, layer: AudioLayerState.Bass)
}
但是我没有得到任何音频播放,任何人都可以发现我的执行出了问题?
编辑:rdelmar答案后
var bassAudio : AVAudioPlayer! = AVAudioPlayer()
class MusicAudio: NSObject, AVAudioPlayerDelegate {
override init() {
super.init()
let bassAudioPath = NSBundle.mainBundle().pathForResource("Raw", ofType:"mp3")
let fileURL = NSURL(fileURLWithPath: bassAudioPath!)
bassAudio = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
bassAudio.currentTime = 0
bassAudio.volume = 1.0
bassAudio.delegate = self
}
func adjustAudioLayerState(volumeOn:Bool, layer:AudioLayerState) {
if layer == AudioLayerState.Bass {
self.bassAudio.prepareToPlay()
self.bassAudio.play()
}
}
}