使用Swift 2.0代码在Xcode 7.1和IOS 9.1中播放嵌入式音频

3

主要是复制和粘贴这段代码。编译并运行,但是没有播放任何声音。使用的是Xcode 7.1和IOS 9.1。我错过了什么...已将声音文件加载到主程序和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
}



}
1个回答

1
您的这行代码反了:

try audioPlayer? = AVAudioPlayer(contentsOfURL: url)

它应该是:

它应该是:

audioPlayer = try AVAudioPlayer(contentsOfURL: url)

顺便提一下:在这里转换成NSString和从NSString转换是不必要的,只需使用String - 你也不应该强制解包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
}

Eric,谢谢。现在完美运行。 - user3069232

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接