Playing Audio in Xcode7

后端 未结 2 988
一个人的身影
一个人的身影 2021-01-27 12:17

I\'m simply trying to play audio when I tap a button, but I get an error with this line of code.

ButtonAudioPlayer = AVAudioPlayer(contentsOfURL: ButtonAudioURL,         


        
相关标签:
2条回答
  • 2021-01-27 12:34

    The AVAudioPlayer class can throw an error, You need to take this into consideration. I personally prefer a do statement which gives the opportunity to catch and handle the error.

    This code worked fine for me:

    import UIKit
    import AVFoundation
    
    class ViewController: UIViewController {
    
        let ButtonAudioURL = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource("test", ofType: "mp3")!)
    
        let ButtonAudioPlayer = AVAudioPlayer()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
    
            do {
                ButtonAudioPlayer = try AVAudioPlayer(contentsOfURL: ButtonAudioURL, fileTypeHint: ".mp3")
    
                ButtonAudioPlayer.play()
            } catch let error {
                print("error loading audio: Error: \(error)")
            }
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    }
    

    You could also make this to an optional, like this:

    ButtonAudioPlayer = try AVAudioPlayer(contentsOfURL: ButtonAudioURL, fileTypeHint: ".mp3")
    ButtonAudioPlayer?.play()
    

    Using this method it will only attempt to play the file if no error was thrown in the previous statement, but will prevent a runtime error.

    0 讨论(0)
  • 2021-01-27 12:35

    You need to use the new Swift 2 syntax by changing that line to

    ButtonAudioPlayer = try! AVAudioPlayer(contentsOfURL: ButtonAudioURL)
    
    0 讨论(0)
提交回复
热议问题