gpt4 book ai didi

swift - 如何使用 Swift 2 在 iOS 应用程序中使用音频?

转载 作者:IT王子 更新时间:2023-10-29 05:33:03 26 4
gpt4 key购买 nike

我使用 SpriteKit 和 Swift 在 Xcode 7 beta 上制作了一个游戏,我尝试将音频放入其中,但这是不可能的,因为 Xcode 发现了 3 个错误,我是初学者,我不知道如何修复它们。

import AVFoundation

var audioPlayer = AVAudioPlayer()


func playAudio() {
// Set the sound file name & extension
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Flip 02", ofType: "wav")!)

// Preperation
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)

// Play the sound
var error: NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
}

代码错误在这里:

代码 1:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)

错误 1:

Extra argument 'error' in call

代码 2:

AVAudioSession.sharedInstance().setActive(true, error: nil)

错误 2:

Extra argument 'error' in call

代码 3:

audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)

错误 3:

Cannot find an initializer for type 'AVAudioPlayer' that accepts an argument list of type '(contentsOfURL: NSURL, error: inout NSError?)'

您的贡献可能会对我有所帮助。谢谢。

最佳答案

使用 do catch 中的函数并使用 try 进行抛出:

var audioPlayer = AVAudioPlayer()

func playAudio() {
do {
if let bundle = NSBundle.mainBundle().pathForResource("Flip 02", ofType: "wav") {
let alertSound = NSURL(fileURLWithPath: bundle)
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
try audioPlayer = AVAudioPlayer(contentsOfURL: alertSound)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
} catch {
print(error)
}
}

参见 this answer获取完整的 Swift 2 错误处理说明。

关于swift - 如何使用 Swift 2 在 iOS 应用程序中使用音频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32332985/

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