2016-11-21 62 views
-1

我对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() 
    } 
} 
+0

只是一个侧面说明,但在命名变量时应遵循一致的命名规则,即'AudioPlayer'应该是'audioPlayer'。 请参阅https://swift.org/documentation/api-design-guidelines/ –

回答

1

对于第一个错误: 参数标签 '(_ :,错误:)' 做 - 额外的参数“错误'in call

Objective C函数,它包含一个错误参数并返回一个布尔值将被标记为一个可能在Swift 3中抛出异常的函数。您可以使用do..try..catch构造来处理错误。

您可以在这里处理错误检查苹果文档: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html

相关AudioPlayer变量是其正在范围之外访问的局部变量的其他错误。

var AudioPlayer = AVAudioPlayer() 

// Declare alertSound at the instance level for use by other functions. 
let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "two", ofType: "mp3")!) 

override func viewDidLoad() { 
    super.viewDidLoad() 

    print(alertSound) 

    do { 
     try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) 
     try AVAudioSession.sharedInstance().setActive(true) 
    } 
    catch { 
     print("ERROR: \(error.localizedDescription)") 
    } 
} 

@IBAction func n2(_ sender: UIButton) { 

    do { 
     AudioPlayer = try AVAudioPlayer(contentsOf: alertSound) 
     AudioPlayer.prepareToPlay() 
     AudioPlayer.play() 
    } 
    catch { 
     print("ERROR: \(error.localizedDescription)") 
    } 
}