2014-10-30 143 views
5

如何使用AVFoundation在Swiftplayground中播放声音文件?理想情况下,该文件将在URL中,而不是在本地驱动器中,但这并不重要。在快速游乐场播放声音

+0

您到目前为止尝试过的任何代码? – 2014-10-30 16:29:37

+0

看看这个链接http://stackoverflow.com/questions/24043904/creating-and-playing-a-sound-in-swift?rq=1 – 2014-10-30 16:33:44

+0

我不确定你可以。 为了确保你能在'playground'内容创建新的文件夹'Resources'进一步游乐场将与路径类似发现: 播放文件:///var/folders/74/d78g19sj65bc6z2n6gjw9n4r0000gn/T/com.apple。 dt.Xcode.pg/applications/YourApp-67685-8.app/Want_You.mp3 但是'avPlayer.prepareToPlay()'将总是返回'false'。 – 2014-10-30 17:05:18

回答

2

我在这个自己的黑暗中摸索着,但我认为这可能是由于快速游乐场的一些限制。考虑以下代码:

#!/usr/bin/swift 

import Cocoa 
import AVFoundation 

var error: NSError? 

println("Hello, Audio!") 
var url = NSURL(fileURLWithPath: "/Users/somebody/myfile.mid") // Change to a local midi file 
var midi = AVMIDIPlayer(contentsOfURL: url, soundBankURL: nil, error: &error) 
if midi == nil { 
    if let e = error { 
     println("AVMIDIPlayer failed: " + e.localizedDescription) 
    } 
} 
midi.play(nil) 
while midi.playing { 
    // Spin (yeah, that's bad!) 
} 

如果我们运行在终端这个迅速脚本,它工作正常,并播放MIDI文件,但如果你运行在一个操场上的代码,你会得到

AVMIDIPlayer失败:操作无法完成。 (com.apple.coreaudio.avfaudio错误-1。)

从积极的方面来看,能够在终端中运行它表明代码确实有效。

+0

我得到了相同的结果... – cfischer 2014-10-31 12:11:53

1

这对我在Playground上没有试过的项目有效。首先将您的声音拖到您的项目中,并根据需要选择复制目标,然后选中“添加到目标”到您的应用程序。

import Cocoa 
import AVFoundation 


var beepSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("beep", ofType: "aif")!) 
func initBeep(){ 
    beepPlayer = AVAudioPlayer(contentsOfURL: beepSound, error: nil) 
    beepPlayer.prepareToPlay() 
} 

func playBeepSound(){ 
    beepPlayer.play() 
} 
func applicationDidFinishLaunching(aNotification: NSNotification?) { 

    initBeep() 
} 
@IBAction func btnPlayBeepSound(sender: AnyObject) { 
    playBeepSound() 
}