Swift 3中的背景音乐

时间:2016-10-24 20:18:08

标签: ios swift swift3

我想在我的游戏中使用Swift 3编写背景音乐。我尝试了很多教程和示例代码,但我找不到一个在我的Swift 3代码中工作的实现。我能找到的最好的示例代码就是这个:

 public void addInv(int ITEM_ID) {
    for(int x = 0; x < MAX_STORAGE; x++) {
       if(isValidID(INVENTORY[x])) {

      }
    }
}

public static boolean isValidID(int X) {
   return true;
}

我已将音乐文件放在名为“资源”的单独文件夹中。如果你能帮助我,我会很高兴的!

我用下划线更改了文件名中的空格,但仍然给出了问题。 顺便说一句,当我按照Xcode的翻译提示时,我得到了这段代码:

lazy var backgroundMusic: AVAudioPlayer? = {
    guard let url = Bundle.main.url(forResource: "Music Title", withExtension: "mp3") else {
        return nil
    }

    do {
        let player = try AVAudioPlayer(contentsOf: url)
        player.numberOfLoops = -1
        return player
    } catch {
        return nil
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    backgroundMusic?.play()
}

lazy var backgroundMusic: AVAudioPlayer? = { guard let url = Bundle.main.url(forResource: "Mining by Moonlight", withExtension: "mp3") else { return nil } do { let player = try AVAudioPlayer(contentsOf: url) player.numberOfLoops = -1 return player } catch { return nil } }() override func viewDidLoad() { super.viewDidLoad() backgroundMusic?.play() } 设置断点并插入代码后,我从调试器获得以下结果:

  

0x1029097d8&lt; + 760&gt;:movq 0x69a9(%rip),%rcx; TabTab.ViewController的直接字段偏移量。(_98A37426C9C75C234890E1E239802C1D中的backgroundMusic.storage):Swift.Optional&gt;

2 个答案:

答案 0 :(得分:2)

在swift 3中

class MusicHelper {
static let sharedHelper = MusicHelper()
var audioPlayer: AVAudioPlayer?
func playBackgroundMusic() {
    let aSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "mario", ofType: "mp3")!)

    print(aSound)
    do {
        audioPlayer = try AVAudioPlayer(contentsOf:aSound as URL)
        audioPlayer!.numberOfLoops = -1
        audioPlayer!.prepareToPlay()
        audioPlayer!.play()
    } catch {
        print("Cannot play the file")
    }
}

}

并在viewdidLoad中添加它 的 MusicHelper.sharedHelper.playBackgroundMusic()

答案 1 :(得分:0)

解决了ALHAMDULELLAH仅在Xcode设置中更改的问题 [![转到设置页>>功能>>背景>>模式>>允许音频文件]