Playing Audio in Xcode7

2019-03-04 03:53发布

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, error: nil)

This is my whole code:

import UIKit
import AVFoundation

class ViewController: UIViewController {

var ButtonAudioURL = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource("Audio File 1", ofType: "mp3")!)

var ButtonAudioPlayer = AVAudioPlayer()



override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    ButtonAudioPlayer = AVAudioPlayer(contentsOfURL: ButtonAudioURL, error:       nil)

}


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

@IBAction func playAudio1(sender: UIButton) {


}

}

The error is

Incorrect argument label in call (have 'contentsOfURL:error:', expected 'contentsOfURL:fileTypeHint:').

When I change error to fileTypeHint, it still does not work.

2条回答
闹够了就滚
2楼-- · 2019-03-04 04:47

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

ButtonAudioPlayer = try! AVAudioPlayer(contentsOfURL: ButtonAudioURL)
查看更多
▲ chillily
3楼-- · 2019-03-04 04:52

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.

查看更多
登录 后发表回答