我对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/ –