Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing an embedded sound using swift 2.0 code Xcode 7.1 IOS 9.1

Copied and Pasted this code principally. Compiles and runs, but plays nothing. Using Xcode 7.1 and IOS 9.1. What have I missed... Loaded sound file into main program and AVAssets...

import UIKit
import AVFoundation

class ViewController: UIViewController {

   var buttonBeep : AVAudioPlayer?

   override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    buttonBeep = setupAudioPlayerWithFile("hotel_transylvania2", type:"mp3")
    //buttonBeep?.volume = 0.9
    buttonBeep?.play()
   }

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

func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer?  {
    //1
    let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
    let url = NSURL.fileURLWithPath(path!)

    //2
    var audioPlayer:AVAudioPlayer?

    // 3
    do {
        try audioPlayer? = AVAudioPlayer(contentsOfURL: url)
    } catch {
        print("Player not available")
    }

    return audioPlayer
}



}
like image 782
user3069232 Avatar asked Jan 30 '26 02:01

user3069232


1 Answers

You've got this line backwards:

try audioPlayer? = AVAudioPlayer(contentsOfURL: url)

It should be:

audioPlayer = try AVAudioPlayer(contentsOfURL: url)

Side note: the conversion to and from NSString is not necessary here, just use String - and you should not force unwrap the result of NSBundle:

func setupAudioPlayerWithFile(file:String, type:String) -> AVAudioPlayer?  {
    //1
    guard let path = NSBundle.mainBundle().pathForResource(file, ofType: type) else {
        return nil
    }
    let url = NSURL.fileURLWithPath(path)

    //2
    var audioPlayer:AVAudioPlayer?

    // 3
    do {
        audioPlayer = try AVAudioPlayer(contentsOfURL: url)
    } catch {
        print("Player not available")
    }

    return audioPlayer
}
like image 165
Eric Aya Avatar answered Jan 31 '26 15:01

Eric Aya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!