2016-04-19 6 views
0

Ich habe drei Tasten und ich versuche, einen Ton zu bekommen, mit jeder Taste zu spielen.Audio nicht im Simulator spielen

Die Sounds spielen nicht im Simulator und fragen sich, was in meinem Code schief gelaufen ist.

import UIKit 
import AVFoundation 

class ViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 
    } 

    @IBAction func mmm_sound(sender: UIButton) { 
     playSound("mmm") 
    } 
     @IBAction func aww_sound(sender: UIButton) { 
     playSound("aww") 
     } 
    @IBAction func maniacal_sound(sender: UIButton) { 
     playSound("hah") 
    } 


    //sound function 
    func playSound(soundName: String) 
    { 

     let sound = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource(soundName, ofType: "wav")!) 
     do{ 
      let audioPlayer = try AVAudioPlayer(contentsOfURL:sound) 
      audioPlayer.prepareToPlay() 
      audioPlayer.play() 
     }catch { 
       print("Error getting the audio file") 
      } 
    } 

} 

Antwort

1

Sie sollten AVAudioPlayer als globale Variable als lokale Variable 'AVAudioPlayer' get ausplanen machen, bevor es spielt, kann der Code wie folgt

//at top 
var audioPlayer = AVAudioPlayer() 

func playSound(soundName: String) 
    { 
     let sound = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource(soundName, ofType:"wav")!) 
     do{ 
      audioPlayer = try AVAudioPlayer(contentsOfURL:sound) 
      audioPlayer.prepareToPlay() 
      audioPlayer.play() 
     }catch { 
      print("Error getting the audio file") 
     } 
    } 
+0

Hey Mann, den ich wirklich Sie schätzen – walton