-3

I am trying to play a sound in my iOS app (written in Swift 2) using AVFoundation. I had it working with no issues with the previous version of Swift. I am using Xcode 7.0. I am not sure what the issue is and cannot find any additional info for Swift 2 regarding playing sounds. Here's my code for the sound part:

import AVFoundation

class ViewController: UIViewController {
    var mySound = AVAudioPlayer()

    override func viewDidLoad() {
            super.viewDidLoad()
        mySound = self.setupAudioPlayerWithFile("mySound", type:"wav")

        mySound.play()
    }

    func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer  {
            var path = NSBundle.mainBundle().pathForResource(file, ofType:type)
            var url = NSURL.fileURLWithPath(path!)

            var error: NSError?

            var audioPlayer:AVAudioPlayer?
            audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)

            return audioPlayer!
    }
}

I am getting this error but have a feeling there maybe some other issue:

'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?

user1822824
  • 2,478
  • 6
  • 41
  • 65
  • Possible duplicate of [How to play a sound in Swift 2.0?](http://stackoverflow.com/questions/32036146/how-to-play-a-sound-in-swift-2-0) – Devapploper Jan 08 '16 at 13:35

2 Answers2

3

Like Leo said

You need to implement do try catch error handling.

Here is another example of some code that will run sound when a button is pressed.

import UIKit
import AVFoundation

class ViewController: UIViewController {


@IBAction func play(sender: AnyObject) {

     player.play()

}

@IBAction func pause(sender: AnyObject) {

    player.pause()

}


var player: AVAudioPlayer = AVAudioPlayer()

override func viewDidLoad() {
    super.viewDidLoad()

    let audioPath = NSBundle.mainBundle().pathForResource("sound", ofType: "mp3")!

    do {

        try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))


    } catch {

        // Process error here

    }


  }

}

I hope this helps!

Rick
  • 114
  • 1
  • 12
2

You need to implement do try catch error handling. Try like this:

func setupAudioPlayerWithFile(file: String, type: String) -> AVAudioPlayer? {

    if let url = NSBundle.mainBundle().URLForResource(file, withExtension: type) {
        do {
            return try AVAudioPlayer(contentsOfURL: url)
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }
    return nil
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571