2016-11-21 98 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)") 
    } 
}