我對Xcode相當新,因此,如果以下需要一個簡單的修復道歉。已經創建了一個簡單的按鈕作爲一個不同的項目的測試,導入在「支持文件」目錄下的MP3文件,下面是我的代碼,由於我遵循的教程提供了一些錯誤,這些錯誤都使用不同版本的Xcode 。試圖播放聲音使用AVFoundation
AVFoundation也被添加到項目中。
錯誤:
Argument labels '(_:, error:)' do -- Extra argument 'error' in call Use of unresolved identifier 'alertSound'
代碼:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var AudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let alertSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "two", ofType: "mp3")!)
print(alertSound)
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func n2(_ sender: UIButton) {
var error:NSError?
AudioPlayer = AVAudioPlayer(contentsOfUrl: alertSound, error: &error)
AudioPlayer.prepareToPlay()
AudioPlayer.play()
}
}
只是一個側面說明,但在命名變量時應遵循一致的命名規則,即'AudioPlayer'應該是'audioPlayer'。 請參閱https://swift.org/documentation/api-design-guidelines/ –