2015-11-07 26 views
3

主要複製並粘貼了此代碼。編譯並運行,但不起作用。使用Xcode 7.1和IOS 9.1。有什麼我錯過了......加載的聲音文件到主程序和AVAssets ...使用swift 2.0代碼播放嵌入式聲音Xcode 7.1 IOS 9.1

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

你有這條線向後:

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 
} 
+0

Eric,謝謝。現在完美運作。 – user3069232

+0

不客氣。 – Moritz