【问题标题】:Swift, how to play sound when press a buttonSwift,按下按钮时如何播放声音
【发布时间】:2014-11-02 09:26:45
【问题描述】:

我是编程的初学者,开始学习 Swift 来制作一个有趣的钢琴应用程序。

我在按下按钮时无法播放声音。 我已经搜索了一些网站,但我太初学者理解......

http://www.tmroyal.com/playing-sounds-in-swift-avaudioplayer.html http://www.rockhoppertech.com/blog/swift-avfoundation/

您能告诉我按“PainoC”按钮时如何播放“C.m4a”声音吗?

这是我的“view controller.swift”。

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()   
    }

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

    @IBAction func PianoC(sender: AnyObject) {
    }
}

【问题讨论】:

    标签: swift


    【解决方案1】:

    希望对你有帮助。

    import UIKit
    import AVFoundation
    
    class ViewController: UIViewController {
       // make sure to add this sound to your project
       var pianoSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("C", ofType: "m4a"))
       var audioPlayer = AVAudioPlayer()
    
       override func viewDidLoad() {
           super.viewDidLoad()   
    
           audioPlayer = AVAudioPlayer(contentsOfURL: pianoSound, error: nil)
           audioPlayer.prepareToPlay()
       }
    
       override func didReceiveMemoryWarning() {
           super.didReceiveMemoryWarning()
       }
    
       @IBAction func PianoC(sender: AnyObject) {
           audioPlayer.play() 
       }
    
    }
    

    最新的 Swift 4.2:

       let pianoSound = URL(fileURLWithPath: Bundle.main.path(forResource: "btn_click_sound", ofType: "mp3")!)
       var audioPlayer = AVAudioPlayer()
    
       @IBAction func PianoC(sender: AnyObject) {
           do {
                audioPlayer = try AVAudioPlayer(contentsOf: pianoSound)
                audioPlayer.play()
           } catch {
              // couldn't load file :(
           } 
       }
    

    【讨论】:

    • 感谢您的回答,非常感谢。对不起,我不习惯添加评论,,,它不起作用,我通过回答来回复你......
    • 在研究了一段时间的 Xcode 和 Swift 之后,现在我明白了你的答案。有效!非常感谢!
    • 为什么要将audioPlayer初始化为AVAudioPlayer()?
    • @jpheldson 是的,我也注意到了。
    【解决方案2】:

    斯威夫特 3

    现在的语法如下: 首先在代码顶部添加import AVFoundation 以访问AVFoundation Framework

    import UIKit
    import AVFoundation
    
    class ViewController: UIViewController {
        //this is your audio playback instance
        var audioPlayer = AVAudioPlayer()
    
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // address of the music file.
            let music = Bundle.main.path(forResource: "Music", ofType: "mp3")
            // copy this syntax, it tells the compiler what to do when action is received
            do {
                audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: music! ))
                try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
                try AVAudioSession.sharedInstance().setActive(true)
            }
            catch{
                print(error)
            }
    
        }
    //this runs the do try statement
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
        @IBAction func play(_ sender: AnyObject) {
            audioPlayer.play()
        }
        @IBAction func stop(_ sender: AnyObject) {
            audioPlayer.stop()
        }
    }
    

    【讨论】:

      【解决方案3】:

      在 Swift 4 中:

      import AVFoundation
      class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate {
          let popSound = Bundle.main.url(forResource: "Pop", withExtension: "mp3")
          var audioPlayer = AVAudioPlayer()
      
        override func viewDidLoad() {
             do {
                  audioPlayer = try AVAudioPlayer(contentsOf: popSound!)
                  audioPlayer.play()
              } catch {
                  print("couldn't load sound file")
              }
      }
      

      【讨论】:

      • 这会崩溃,因为它为 popSound 返回 nil。这可以使用以下代码轻松修复:let popSound = Bundle.main.path(forResource: "pop.mp3", ofType:nil)!audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: popSound))
      • 请避免强制解包值,因为这是一种危险的操作,可能会导致应用程序意外崩溃。永远记住编写尽可能安全的代码。
      【解决方案4】:
      import UIKit
      import AVFoundation
      
      class ViewController: UIViewController {
          var audioPlayer = AVAudioPlayer()
      
          override func viewDidLoad() {
              super.viewDidLoad()
              // Do any additional setup after loading the view, typically from a nib.
          }
      
          override func didReceiveMemoryWarning() {
              super.didReceiveMemoryWarning()
              // Dispose of any resources that can be recreated.
          }
      
          @IBAction func button1Action(sender: AnyObject) {
              let CatSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Meow-sounds", ofType: "mp3")!)
              do {
                  audioPlayer = try AVAudioPlayer(contentsOfURL: CatSound)
                  audioPlayer.prepareToPlay()
              } catch {
                  print("Problem in getting File")
              }
              audioPlayer.play()
          }
      }
      

      【讨论】:

      • 请不要发帖similar answers。无论如何,如果某个问题已经有答案,请将该问题标记为重复,而不是回答。谢谢。
      • @Eric Aya 看看我的代码.. 它与上面的答案不同.. 我使用 try 和 catch 方法进行错误处理,这在 x-code 版本 7.1 (7B91b) 中对于新的 swift
      • 我说的不是这里的答案。问题是您在另一页上发布了一个与您已经发布的答案相似的答案。这就是为什么我告诉你不要发布重复的内容并标记问题。
      【解决方案5】:

      在 Swift 4 中

      这对我有用,试试吧。

      import UIKit
      import AVFoundation
      
      class ViewController: UIViewController, AVAudioPlayerDelegate{
      
          var audioPlayer = AVAudioPlayer()
      
          override func viewDidLoad() {
              super.viewDidLoad()
          }
      
      
      
          @IBAction func notePressed(_ sender: UIButton) {
      
              let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "note1", ofType: "wav")!)
      
              do{
                  audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)
      
              }catch {
                  print("there was some error. The error was \(error)")
              }
              audioPlayer.play()
      
          }
      
      
      
      }
      

      【讨论】:

        【解决方案6】:

        SWIFT 5

        import AVFoundation
        
        
        class Test {
            
            var player: AVAudioPlayer!
            
            func playAudio() {
                
                let url = Bundle.main.url(forResource: "Sound", withExtension: "mp3")
                player = try! AVAudioPlayer(contentsOf: url!)
                player.play()
                
                
            }
            
        }
        

        【讨论】:

          【解决方案7】:

          在 Swift 3 中:

          import UIKit
          import AVFoundation
          
          class QuestionView: UIViewController {
          
              var btnButton = UIButton()
              var player = AVAudioPlayer()
          
              override func viewDidLoad() {
                  super.viewDidLoad()
          
                  btnButton.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
                  btnButton.backgroundColor = UIColor.blue
                  btnButton.addTarget(self, action: #selector(ButtonSound), for: .touchUpInside)
          
              }
          
              func ButtonSound() {
          
                 do {
          
                     //  make sure to add this sound to your project
          
                     let audioPath = Bundle.main.path(forResource: "Click", ofType: "mp3")
          
                     try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPath!) as URL)
          
          
                 } catch {
          
                     print("Error !")
          
                 }
          
                 player.play()
          
              }
          
          }
          

          【讨论】:

            【解决方案8】:

            如果你只想要点击效果,下面的代码就可以了。
            小鸟文件必须在 xcode 中。

            self.run(SKAction.playSoundFileNamed("Bird.mp3", waitForCompletion:false))
            

            【讨论】:

              猜你喜欢
              • 2015-05-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多