2015-09-01 18 views
9

Ho creato un gioco su Xcode 7 beta usando SpriteKit e Swift, ho provato a inserire Audio ma non è possibile perché Xcode ha trovato 3 errori, sono principiante e non so come risolverli.Come utilizzare l'audio nell'applicazione iOS con Swift 2?

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() 
} 

L'errore di codice sono qui:

Codice 1:

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

di errore 1:

Extra argument 'error' in call

Codice 2:

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

Errore 2:

Extra argument 'error' in call

Codice 3:

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

Errore 3:

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

Il tuo contributo potrebbe aiutarmi. Grazie.

+0

possibile duplicato del [Swift non-try-catch sintassi] (http://stackoverflow.com/questions/30720497/swift-do-try-catch-syntax) – nalply

risposta

6

La gestione degli errori in Swift 2.0 è stata modificata. Foundation e altri framework di sistema ora utilizzano un nuovo tipo di gestione degli errori che utilizza il meccanismo try and catch.

In Cocoa, methods that produce errors take an NSError pointer parameter last parameter, which populates its argument with an NSError object if an error occurs. Swift automatically translates Objective-C methods that produce errors into methods that throw an error according to Swift’s native error handling functionality.

Se si guarda la definizione di funzioni che si utilizza si può vedere che ora lanciano. Ad esempio:

public func setActive(active: Bool) throws 

Si può vedere che non ci sono parametri di errore poiché la funzione genera errore. Ciò riduce notevolmente il dolore nella gestione di NSError e riduce anche la quantità di codice che è necessario scrivere.

Quindi ovunque si visualizzi l'errore come ultimo parametro della funzione, eliminarlo e scrivere provare! davanti ad esso. Un esempio è questo:

try! AVAudioSession.sharedInstance().setActive(true) 

Dal momento che la gestione degli errori non è portata di questa domanda, si può leggere di più su di esso here.

Questo è corretto versione del codice che hai scritto:

import AVFoundation 

var audioPlayer = AVAudioPlayer() 

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

    // Preperation 
    try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: []) 
    try! AVAudioSession.sharedInstance().setActive(true) 

    // Play the sound 
    do { 
     try audioPlayer = AVAudioPlayer(contentsOfURL: alertSound) 
     audioPlayer.prepareToPlay() 
     audioPlayer.play() 
    } catch { 
     print("there is \(error)") 
    } 
} 
24

utilizzare le funzioni all'interno do catch e utilizzare try per quelle da lancio:

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) 
    } 
} 

Vedi this answer per un completo errore Swift 2 gestire le spiegazioni.

+0

Sta funzionando, ma non hai mostrato come fare audio per riprodurlo da solo tutto il tempo. –

+1

Ho trovato la soluzione da solo. E per la ripetizione basta aggiungere: audioPlayer.numberOfLoops = -1. Grazie per il tuo contributo. –

0

L'idea è di creare un'estensione di AVAudioPlayer e utilizzare un metodo per chiamare qualsiasi classe.

1) Creare una classe swift vuota denominata "AppExtensions". Aggiungi il seguente.

// AppExtensions.swift 

    import Foundation 
    import UIKit 
    import SpriteKit 
    import AVFoundation 

    //Audio 
    var audioPlayer = AVAudioPlayer() 

    extension AVAudioPlayer { 

     func playMusic(audioFileName:String,audioFileType:String) 
     {  
      do { 

      let alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(audioFileName, ofType: audioFileType)!) 

      // Removed deprecated use of AVAudioSessionDelegate protocol 
      try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) 
      try AVAudioSession.sharedInstance().setActive(true) 
      try audioPlayer = AVAudioPlayer(contentsOfURL: alertSound) 
      audioPlayer.prepareToPlay() 
      audioPlayer.play() 

      } 
      catch { 
       print(error) 
      } 
    } 
    } 

2) Chiamare il metodo di estensione in qualsiasi classe.

var audioPlayer1 = AVAudioPlayer() 
audioPlayer1.playMusic(audioFileName:"tik",audioFileType:"wav") 
Problemi correlati