Swift 2 + Xcode 7:按下错误按钮时播放声音

Posted

技术标签:

【中文标题】Swift 2 + Xcode 7:按下错误按钮时播放声音【英文标题】:Swift 2 + Xcode 7: Sound playing when wrong button is pressed 【发布时间】:2015-10-11 19:01:27 【问题描述】:

我正在编程和学习的一个小应用程序有问题。我终于添加了一个声音,它应该在你按下步进器时播放,它确实如此,问题是当你按下不同的按钮时它也在播放。 老实说,我不知道它为什么会发生以及如何解决它。 有什么帮助吗?

这是我的代码:

ViewONE(此处不应播放音频文件的按钮是“BotonLetsBegin”

//
//  ViewONE.swift
//  Simple Score
//
//  Created by Juan Francisco Mellado on 10/1/15.
//  Copyright © 2015 Juan Francisco Mellado. All rights reserved.
//

import Foundation
import UIKit

class ViewONE: UIViewController, UITextFieldDelegate 


    override func preferredStatusBarStyle() -> UIStatusBarStyle 
        return UIStatusBarStyle.LightContent
    

    @IBOutlet weak var ScrollViewOne: UIScrollView!
    @IBOutlet weak var teamRedName: UITextField!
    @IBOutlet weak var initScoreRed: UITextField!

    @IBAction func BotonLetsBeginAction(sender: UIButton) 

    

    @IBOutlet weak var BotonLetsBegin: UIButton!


    @IBOutlet weak var teamBlueName: UITextField!
    @IBOutlet weak var initScoreBlue: UITextField!


    @IBAction func userTappedBackground(sender: AnyObject) 
        view.endEditing(true)
    

    @IBAction func userTappedThisView(sender: AnyObject) 
        view.endEditing(true)
    

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) 
        let DestViewController : ViewTwo = segue.destinationViewController as! ViewTwo

        // Cambiamos los valores si no existen a 0

        if(initScoreRed.text == "")
            initScoreRed.text = "0"
        
        if(initScoreBlue.text == "")
            initScoreBlue.text = "0"
        
        //---------

        DestViewController.RedName = teamRedName.text!
        DestViewController.BlueName = teamBlueName.text!
        DestViewController.RedScore = initScoreRed.text!
        DestViewController.BlueScore = initScoreBlue.text!

    



    override func viewDidLoad() 
        super.viewDidLoad()

        let value = UIInterfaceOrientation.Portrait.rawValue
        UIDevice.currentDevice().setValue(value, forKey: "orientation")
        BotonLetsBegin.layer.cornerRadius = 5

        self.initScoreBlue.delegate = self
        self.initScoreRed.delegate = self

    

    let TEXT_FIELD_LIMIT = 3

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool 

    switch textField 
    case initScoreBlue:
        return (textField.text?.utf16.count ?? 0) + string.utf16.count - range.length <= TEXT_FIELD_LIMIT
    case initScoreRed:
        return (textField.text?.utf16.count ?? 0) + string.utf16.count - range.length <= TEXT_FIELD_LIMIT
    case teamBlueName:
        return (textField.text?.utf16.count ?? 0) + string.utf16.count - range.length <= 25
    case teamRedName:
        return (textField.text?.utf16.count ?? 0) + string.utf16.count - range.length <= 25
    default:
        return true
    


    //For Swift 1.2
    //return count((textField.text ?? "").utf16) + count(string.utf16) - range.length <= TEXT_FIELD_LIMIT

    override func shouldAutorotate() -> Bool 
        return false
    
    func textFieldDidBeginEditing(textField: UITextField) 

        if (textField == initScoreBlue)
            ScrollViewOne.setContentOffset(CGPointMake(0, 250), animated: true)
        
        if (textField == teamBlueName)
            ScrollViewOne.setContentOffset(CGPointMake(0, 250), animated: true)
        
        if (textField == teamRedName)
            ScrollViewOne.setContentOffset(CGPointMake(0, 100), animated: true)
        
        if (textField == initScoreRed)
            ScrollViewOne.setContentOffset(CGPointMake(0, 100), animated: true)
        
    
    func textFieldShouldReturn(textField: UITextField) -> Bool 
        textField.resignFirstResponder()
        return true
    
    func textFieldDidEndEditing(textField: UITextField) 
        ScrollViewOne.setContentOffset(CGPointMake(0, 0), animated: true)
    

    // - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    //
    //[textField resignFirstResponder];
    //


这是步进器所在的 ViewTwo

//
//  ViewTWO.swift
//  Simple Score
//
//  Created by Juan Francisco Mellado on 9/29/15.
//  Copyright © 2015 Juan Francisco Mellado. All rights reserved.
//

import Foundation
import UIKit
import AVFoundation


class ViewTwo : UIViewController, AVAudioPlayerDelegate 

    override func preferredStatusBarStyle() -> UIStatusBarStyle 
        return UIStatusBarStyle.LightContent
    

    /// Actions de sonido -------
    @IBAction func stepperSoundRed(sender: UIStepper) 
        audioPlayer.play()
    
    @IBAction func stepperSoundBlue(sender: UIStepper) 
        audioPlayer.play()
    
    /////////////////////////

    // el nombre del equipo Blue
    @IBOutlet weak var teamBlueTextLabel: UILabel!
    var BlueName = String()

    // nombre del equipo rojo
    @IBOutlet weak var teamRedTextLabel: UILabel!
    var RedName = String()

    // score inicial del equipo rojo
    @IBOutlet weak var RedScoreLabel: UILabel!
    var RedScore = String()

    // score initcial equipo azul
    @IBOutlet weak var BlueScoreLabel: UILabel!
    var BlueScore = String()

    // que funcionen los Steppers
    @IBOutlet weak var RedStepperUI: UIStepper!
    @IBOutlet weak var BlueStepperUI: UIStepper!

    // Botón Done
    @IBOutlet weak var BotonDone: UIButton!

    @IBAction func BlueStepperValueChange(sender: UIStepper) 
        BlueScoreLabel.text  = Int(sender.value).description
    

    @IBAction func RedStepperValueChange(sender: UIStepper) 
        RedScoreLabel.text  = Int(sender.value).description

    
   // archivos de sonidos
    var sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("ping2", ofType: "mp3")!)
    var audioPlayer = AVAudioPlayer()

    required init? (coder aDecoder: NSCoder)
        super.init(coder: aDecoder)
        do 
            try audioPlayer = AVAudioPlayer(contentsOfURL: sound, fileTypeHint: nil)
            audioPlayer.prepareToPlay()
            audioPlayer.delegate = self
            audioPlayer.play()

         catch 
            // Errors here
        
    

    // VIEW DID LOAD
    override func viewDidLoad() 
        // No se para que es esto??
        super.viewDidLoad()

        BotonDone.layer.cornerRadius = 5

        // Checamos si están vacios los nombres
        if BlueName.isEmpty 
            BlueName = "TEAM BLUE"
        

        if RedName.isEmpty 
            RedName = "TEAM RED"
        


        // Proseguimos a asignarlos a las Labels

        teamBlueTextLabel.text = BlueName
        teamRedTextLabel.text = RedName
        RedScoreLabel.text = RedScore
        BlueScoreLabel.text = BlueScore


        // Aqui vemos el Red +/-
        RedStepperUI.wraps = true
        RedStepperUI.autorepeat = false
        RedStepperUI.value = Double(RedScore)!
        RedStepperUI.maximumValue = 999

        // aqui vemos el Blue +/-
        BlueStepperUI.wraps = true
        BlueStepperUI.autorepeat = false
        BlueStepperUI.value = Double(BlueScore)!
        BlueStepperUI.maximumValue = 999

        //
        let value = UIInterfaceOrientation.LandscapeLeft.rawValue
        UIDevice.currentDevice().setValue(value, forKey: "orientation")
    
    override func shouldAutorotate() -> Bool 
        return false
    

【问题讨论】:

【参考方案1】:

您的问题出在 ViewTwo 的 init(...) 方法中。你创建一个播放器并调用 play() 方法:

required init? (coder aDecoder: NSCoder)
    super.init(coder: aDecoder)
    do 
        try audioPlayer = AVAudioPlayer(contentsOfURL: sound, fileTypeHint: nil)
        audioPlayer.prepareToPlay()
        audioPlayer.delegate = self

        audioPlayer.play() // this is your problem ;)

     catch 
        // Errors here
    

【讨论】:

太棒了!非常感谢你。它起作用了,另一件事。当我向 var BlueScore 输入一个值时,如果它大于 100,那么只要我按下“+”步进器,它就会回到 100……知道为什么吗?

以上是关于Swift 2 + Xcode 7:按下错误按钮时播放声音的主要内容,如果未能解决你的问题,请参考以下文章

如何将LUT(从.png)应用到图像? (Swift + Xcode)

xcode swift不会更改标签文本

当按下按钮但卡住时,尝试在UIView.animate中更改按钮标题和label.center.x.为什么? Swift 4 Xcode 9.4

音频播放错误 - XCODE 7 (Swift 2.0)

如何使用 Swift 2(Xcode 7)在我的 Sprite Kit 游戏中为背景音乐设置静音按钮?

Xcode Swift UITableView:表格不出现