SKAudioNode 无法从 url 加载声音

SKAudioNode not load sound from url

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

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

sound.run(SKAction.play())

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

但是这段代码导致错误:

Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: file != nil' *** First throw call stack: ....

libc++abi.dylib: terminating with uncaught exception of type NSException

我想你试试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()
}

我认为 URL 需要 os URL 来获取应用程序包中必须包含的资源。将 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())