简体   繁体   中英

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
}



}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM