gpt4 book ai didi

ios - 如何用swift 2.0播放背景音乐?

转载 作者:搜寻专家 更新时间:2023-11-01 05:45:26 28 4
gpt4 key购买 nike

嗨,我是 swift 和 ios 开发的新手。在我更新到 Swift 2.0 之前,我的代码一直在运行,我使用了快速迁移工具,但我仍然不知道如何整理和修复我的代码。请帮忙!

import AVFoundation

var backgroundMusicP: AVAudioPlayer!

func playBackgroundMusic(filename: String) {
let url = NSBundle.mainBundle().URLForResource(
filename, withExtension: nil)
if (url == nil) {
print("Could not find file: \(filename)")
return
}

var error: NSError?

do {

backgroundMusicP = try AVAudioPlayer(contentsOfURL: url!)
} catch {

backgroundMusicP == nil
}
if backgroundMusicP == nil {
print("Could not create audio player: \(error)")
return
}

backgroundMusicP.numberOfLoops = -1
backgroundMusicP.prepareToPlay()
backgroundMusicP.play()
}

最佳答案

swift 2.0 的更新函数:

import AVFoundation

var backgroundMusicPlayer = AVAudioPlayer()

func playBackgroundMusic(filename: String) {
let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
guard let newURL = url else {
print("Could not find file: \(filename)")
return
}
do {
backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: newURL)
backgroundMusicPlayer.numberOfLoops = -1
backgroundMusicPlayer.prepareToPlay()
backgroundMusicPlayer.play()
} catch let error as NSError {
print(error.description)
}
}

这样使用:

playBackgroundMusic("yourFileName.mp3")

关于ios - 如何用swift 2.0播放背景音乐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32882737/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com