2016-03-02 111 views
1

大家好,我試圖在啓動時自動播放xcode遊戲中的聲音,並且我嘗試了一堆不同的代碼。我可以在Objective-C中編寫和運行它,就像下面的viewdidload方法一樣,我爲聲音本身創建了一個方法,並在viewdidload中調用了它。在swift中自動播放聲音

-(void)Loadingsound { 

AudioServicesPlaySystemSound(Loadingsound); 

} 

-(void)viewDidLoad { 

[super viewDidLoad]; 

NSURL *LoadingSound = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Tap Sound" ofType:@"wav"]]; 

AudioServicesCreateSystemSoundID((__bridge CFURLRef)LoadingSound, &Loadingsound); 

[self Loadingsound]; 

但現在我試圖在swift中複製相同的內容,但我無法這樣做。我在下面的另一個關於堆棧溢出問題中看到了下面的代碼,但是從現在開始,這是在Xcode 7.2.1和Swift 2.0上,是否有可能有新的寫法呢?這是我嘗試的代碼,當遊戲開始時聲音無法加載。

override func viewDidLoad() { 

    super.viewDidLoad() 


if let soundURL = NSBundle.mainBundle().URLForResource("Tap Sound", withExtension: "wav") { 
     var mySound: SystemSoundID = 0 

     AudioServicesCreateSystemSoundID(soundURL, &mySound) 

     // Play 

     AudioServicesPlaySystemSound(mySound); 
} 

也是另一種方式,我試圖運行的代碼是......

覆蓋FUNC viewDidLoad中(){

super.viewDidLoad() 

var loadingsound = NSURL(fileURLWithPath: 

NSBundle.mainBundle().pathForResource("Tap Sound", ofType: "wav")) 

    var audioPlayer = AVAudioPlayer() 

     audioPlayer = AVAudioPlayer(contentsOfURL: loadingsound, error: nil) 
     audioPlayer.prepareToPlay() 

     audioPlayer.play() 

在這種方法中,當我嘗試運行它,在符合規定和失敗顯示一個錯誤,告訴我把一個「!」在「wav」中綁定並在此之後放置支架後簽字。在我輸入感嘆號後,它告訴我將下面的「錯誤」一詞替換爲putty「filetypeHint」。有人請幫我解決這個問題。原文在Objective-C中工作得很好,有人可以幫我翻譯精確的代碼來快速翻譯。我看到的其他例子顯示錯誤。

謝謝!

回答

2

檢查您的「Tap Sound」聲音文件是否在您的項目目標中。你需要通過URLForResource加載,並在我的情況下不要設置擴展類型。你只需要文件名。你可以把它放在這樣的方法中。

func playMusic(filename: String) { 
    var audioPlayer: AVAudioPlayer? 
    let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil) 
    if (url == nil) { 
     print("Could not find file: \(filename)") 
     return 
    } 

    do { 
     try audioPlayer = AVAudioPlayer(contentsOfURL: url!) 
     let player = audioPlayer 

     // From Documentation: Negative integer value to loop the sound indefinitely until you call the stop method. 
     player!.numberOfLoops = -1 
     player!.prepareToPlay() 
     player!.play() 
    } catch _ { 
     audioPlayer = nil; 
    } 
} 

// call the function with your soundfile 
playMusic("Tap Sound") 
+0

非常感謝!我嘗試了我們的代碼,並且像使用playMusic(「Tap Sound」)那樣在viewdidload中運行了該方法,並且它在應用程序啓動時起作用了!在它無法在目標中找到文件之前,現在它是。非常感謝您的幫助兄弟! – Dev

+0

是的,它很好,它可以幫助你。 – ronatory