2016-04-19 22 views
0

私は3つのボタンがあり、それぞれのボタンで再生するサウンドを得ようとしています。シミュレータでオーディオが再生されない

私のコードで何がうまくいかないのか疑問に思っています。

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

} 

答えて

1

あなたはそれを果たしている前に、あなたのコードは、この

//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

が好きなことができます「AVAudioPlayer」GET DEALLOCATEのローカル変数としてグローバル変数としてAVAudioPlayerをしなければならない男ねえ、私は本当にあなたに感謝 – walton

関連する問題