SKAudioNode不加载来自网址的声音

时间:2016-10-11 08:34:17

标签: ios swift skaudionode

我想从网址下载声音并播放一次:

let sound = SKAudioNode(url:URL(string:"http://www.music.helsinki.fi/tmt/opetus/uusmedia/esim/a2002011001-e02-16kHz.wav")!)

sound.run(SKAction.play())

我也尝试了.mp3音乐。它不会下载或流式传输并返回:nil

但是这段代码会导致错误:

  

由于未捕获的异常而终止应用   'com.apple.coreaudio.avfaudio',原因:'所需条件为假:   file!= nil'   ***首先抛出调用堆栈:....

     

libc ++ abi.dylib:以未捕获的类型异常终止   NSException

2 个答案:

答案 0 :(得分:1)

我想你试试AVAudioPlayer

var resourcePath = url  //your url
var objectData = Data(contentsOf: NSURL(string: resourcePath)!)
var error: Error!
do {
    audioPlayer = try AVAudioPlayer(objectData)
}
catch let error {
}
audioPlayer.numberOfLoops = 0
audioPlayer.volume = 1.0
audioPlayer.prepareToPlay()
if audioPlayer == nil {
    print("\(error.description)")
}
else {
    audioPlayer.play()
}

答案 1 :(得分:0)

我认为所需的网址是您在应用包中必须拥有的资源的网址。将mp3文件放入项目中,然后执行此操作 -

let urlpath = Bundle.main.path(forResource: "[name of file]", ofType: "mp3")
let audioURL = NSURL.fileURL(withPath: urlpath!)

let sound = SKAudioNode(url: audioURL)

sound.run(SKAction.play())