【问题标题】:Playing a sound in a Swift Playground在 Swift Playground 中播放声音
【发布时间】:2014-12-26 18:37:20
【问题描述】:

如何在Swift playground 中使用 AVFoundation 播放声音文件?理想情况下,文件应该在 URL 中,而不是在本地驱动器中,但这并不重要。

【问题讨论】:

  • 到目前为止您尝试过任何代码吗?
  • 我不确定你是否可以。当然,您可以在playground 内容下创建新文件夹Resources,进一步的 Playground 会发现它的路径如下:正在播放文件:///var/folders/74/d78g19sj65bc6z2n6gjw9n4r0000gn/T/com.apple.dt.Xcode。 pg/applications/YourApp-67685-8.app/Want_You.mp3 但avPlayer.prepareToPlay() 将始终返回false
  • 是的,恐怕这一定是操场实现中的一个错误

标签: swift


【解决方案1】:

我自己在黑暗中摸索这个,但我认为这可能是由于 swift 游乐场的某些限制。考虑这段代码:

#!/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!)
}

如果我们在终端运行这个 swift 脚本,它可以正常工作并播放 MIDI 文件,但如果你在游乐场运行代码,你会得到

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

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

【讨论】:

    【解决方案2】:

    这适用于我尚未在 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()
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-28
      • 1970-01-01
      • 1970-01-01
      • 2014-08-14
      • 2015-01-02
      • 2016-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多