gpt4 book ai didi

ios - AVAudioPlayer 对象声音未播放 - Swift

转载 作者:行者123 更新时间:2023-12-01 18:13:17 25 4
gpt4 key购买 nike

我在下面创建了一个 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()
}
}
}

为了播放噪音,我通过以下方式调用类(class):
@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()
}
}
}

最佳答案

您没有听到任何声音,因为您的 MusicAudio 类正在被释放。您需要制作 var、sound、属性,而不是局部变量。

class ViewController: UIViewController {

var sound = MusicAudio()

@IBAction func testSound() {
self.sound.adjustAudioLayerState(true, layer: AudioLayerState.Bass)
}

}

关于ios - AVAudioPlayer 对象声音未播放 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26302996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com