2016-07-06 2 views
0

나는 사용자로부터 이름을 얻고 썸네일을 선택하기 위해 앱을 만들고있다. 문제는 각 버튼마다 다른 사운드를 재생할 수 없다는 것입니다. 그것은 내가 값을 입력 한 마지막 것입니다 (이 경우, 복수 자). 나는 지난 주 Swift를 시작했는데 언어에 대해 많이 알지 못합니다. 나는 대부분 시간을 google. 여기 내 코드가있다. 미리 감사드립니다.각 버튼에 소리 추가하기

import UIKit 
import AVFoundation 

class ImagesViewController: UIViewController, AVAudioPlayerDelegate { 

    var audioPlayer: AVAudioPlayer? 

    @IBAction func antman(sender: AnyObject) { 
     audioPlayer!.play() 
    } 
    @IBAction func avengers(sender: AnyObject) { 
     audioPlayer!.play() 
    } 

    func selectSound(alertSound: String, sound: String) { 

     var alertSound: NSURL = NSURL (fileURLWithPath: NSBundle.mainBundle().pathForResource(sound, ofType: "mp3")!) 

     var error: NSError? 
     do { 
      audioPlayer = try AVAudioPlayer(contentsOfURL: alertSound) 
     } 
     catch var error1 as NSError { 
      error = error1 
      audioPlayer = nil 
     } 

     audioPlayer!.delegate = self 
     audioPlayer!.prepareToPlay() 

    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // Do any additional setup after loading the view. 

     selectSound("1", sound: "antman") 
     selectSound("2", sound: "avengers") 
    } 


    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) { 

    } 

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
     let newVC: Results = segue.destinationViewController as! Results 
     print("xxx ,%s", segue.identifier) 

     newVC.receivedFirstName = segue.identifier! 
    } 


    /* 
    // MARK: - Navigation 

    // In a storyboard-based application, you will often want to do a little preparation before navigation 
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
     // Get the new view controller using segue.destinationViewController. 
     // Pass the selected object to the new view controller. 
    } 
    */ 

} 
+0

을, 당신은 두 번 초기화 : 한 번에 "복수 자"antman "두 번째 시간 . " 따라서'audioPlayer! .play()'를 호출하면'audioPlayer'에서 초기화 된 마지막 사운드를 검색하여 재생합니다. 별도의 두 개의 'AVAudioPlayer' 속성을 초기화하거나 버튼을 누를 때 올바른 사운드로 AVAudioPlayer를 초기화 할 수 있습니다. 버튼 누름에 반응하는 작은 소리는 충분히 잘 수행 될 수 있습니다. – Palpatim

답변

0

당신은 같은 것을 할 수 있습니다 : 당신은 당신의 뷰 컨트롤러에 하나의`audioPlayer` 속성이

@IBAction func antman(sender: AnyObject) { 
     selectSound("1", sound: "antman") 
     audioPlayer!.play() 
    } 
    @IBAction func avengers(sender: AnyObject) { 
     selectSound("2", sound: "avengers") 
     audioPlayer!.play() 
    } 
관련 문제