我一直想找到一种方法来暂停我的音频按钮(非常简单,只需点击backgroundMusic.stop())但它不会暂停。使用下面的代码,它的想法是它从应用程序的开头运行,但当我再次加载场景时,它不会在上一首曲目的顶部播放。下面的所有代码都是打印' play'每次我加载场景时,我都会让多个曲目互相播放,所以它似乎无法检测音频是否正在播放。这是我第一次在xcode中使用音频,所以我不熟悉它。我正在使用xCode 7.0.1和Swift 2。
在我的ViewController类中,但在我的ViewDidLoad之外:
func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer? {
//1
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
let url = NSURL.fileURLWithPath(path!)
//2
var audioPlayer:AVAudioPlayer?
// 3
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: url)
} catch {
print("Player not available")
}
return audioPlayer
}
在我的ViewDidLoad中:
if let backgroundMusic = self.setupAudioPlayerWithFile("Kawai Kitsune", type:"mp3") {
self.backgroundMusic = backgroundMusic
}
if backgroundMusic != nil {
if backgroundMusic?.playing == false{
backgroundMusic?.volume = 0.1
backgroundMusic?.play()
print("play")
}
else {
print("playing")
}
}
答案 0 :(得分:0)
在课程级别创建AVAudioPlayer
对象,然后尝试。它应该工作!
这样的事情:
class MyController : UIViewController {
var audioPlayer:AVAudioPlayer?
func setupAudioPlayerWithFile(file:NSString, type:NSString) {
//1
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
let url = NSURL.fileURLWithPath(path!)
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: url)
} catch {
print("Player not available")
}
}
override func viewDidLoad() {
self.setupAudioPlayerWithFile("Kawai Kitsune", type:"mp3")
if self.audioPlayer != nil {
if self.audioPlayer?.playing == false {
self.audioPlayer?.volume = 0.1
self.audioPlayer?.play()
print("play")
}
else {
print("playing")
}
}
}
}