2015-12-09 61 views
1

我只是試驗了一下Swift(第一次)。除了錯誤檢查和正確的應用程序結構,我認爲這應該播放音頻:AVFoundation - 播放wav文件(外部應用程序包)Swift 2.1

import Foundation 
import AVFoundation 

var audioPlayer: AVAudioPlayer! 
let file = "/Users/mtwomey/Desktop/test1/test1/a2002011001-e02.wav" 

let url = NSURL(fileURLWithPath: file) 
print(url) 
audioPlayer = try! AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: file), fileTypeHint: "wav") 
audioPlayer.play() 
print("Done.") 

但它並不是。當我運行這個應用程序時,它簡單地繼續打印「完成」。並退出。如果文件名/文件路徑不正確,我會得到一個異常(因此它實際上正在訪問該文件)。

我試圖證明一個控制檯應用程序的概念,它需要訪問應用程序包之外的wave文件。關於我失蹤的任何提示?

+0

遊樂場是沙盒。你有沒有嘗試過一個真正的OSX項目? –

+0

@LeoDabus - 是的,我在Xcode(7.1.1)中正確運行它,上面是單個源文件(main.swift)的全部內容。 – MPT

+0

我的意思是一個窗口/視圖,而不是操場的完整項目 –

回答

0

試試這個,

import UIKit 
import AVFoundation 

class ViewController: AVAudioPlayerDelegate{ 
var audioPlayer: AVAudioPlayer! // Declaring this outside your function, as class variable is important! otherwise your player won't be able to play the sound. 

override func viewDidLoad() { 
    super.viewDidLoad() 
    self.playSound("/Users/mtwomey/Desktop/test1/test1/a2002011001-e02.wav") 
} 

func playSound(soundPath: String) 
{ 
    let sound = NSURL(fileURLWithPath: soundPath) 
    do{ 
     audioPlayer = try AVAudioPlayer(contentsOfURL: sound, fileTypeHint: "wav") 
     audioPlayer.prepareToPlay() 
     audioPlayer.delegate = self 
     audioPlayer.play() 
    }catch { 
     print("Error getting the audio file") 
    } 
} 

或者(如果你已經擺在你的項目中的文件)(關注這個blog post找出如何將文件放置在您的項目)

import UIKit 
import AVFoundation 

class ViewController: AVAudioPlayerDelegate{ 
var audioPlayer: AVAudioPlayer! // Declaring this outside your function, as class variable is important! otherwise your player won't be able to play the sound. 

override func viewDidLoad() { 
    super.viewDidLoad() 
    self.playSound("sound-name") 
} 

func playSound(soundName: String) 
{ 
    let sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundName, ofType: "wav")!) 
    do{ 
     audioPlayer = try AVAudioPlayer(contentsOfURL: sound, fileTypeHint: "wav") 
     audioPlayer.prepareToPlay() 
     audioPlayer.delegate = self 
     audioPlayer.play() 
    }catch { 
     print("Error getting the audio file") 
    } 
} 
+0

這是一個Mac控制檯/命令行應用程序,雖然(不是手機) - 我試圖調整我從你的答案中得到的提示。 – MPT

+0

我不知道,也許這只是錯誤的用例。也許我應該回到C++的控制檯應用程序。由於這涉及到音頻,我認爲我可以用Swift節省時間。 – MPT