如何在Xcode 6.4 Swift app中添加播放背景音乐?

时间:2015-09-08 06:40:37

标签: ios swift background

我不知道如何在Swift中为我的应用(游戏)添加背景音乐。当我运行它时,必须播放背景音乐。几年前我在Xcode工作,但现在它改变了,这是一个废话。我的应用没有音乐。在互联网搜索中,我没有找到答案。当你按下按钮时,大多数答案都会连接音乐播放(我不需要它),当我的应用运行时,我需要在后台播放音乐。

2 个答案:

答案 0 :(得分:0)

使用AVAudioPlayer

let path = NSBundle.mainBundle().pathForResource("mySound", ofType: "mySound")
let Url = NSURL(fileURLWithPath: soundFilePath!)
let mediaPlayer = AVAudioPlayer(contentsOfURL: soundFileURL, error: nil)
player.numberOfLoops = -1 //anything less than 0 cause it to unlimited looping
player.play()

导入AvFoundation !!!!

答案 1 :(得分:0)

Swift 4.2更新 ****新建一个班级,然后粘贴以下代码:........... ****

import AVFoundation

class MusicHelper {
static let sharedHelper = MusicHelper()
var audioPlayer: AVAudioPlayer?

func playBackgroundMusic() {
let aSound = NSURL(fileURLWithPath: 
Bundle.main.path(forResource: "MUSICNAME", ofType: "mp3")!) //change the file name as your file
do {
    audioPlayer = try AVAudioPlayer(contentsOf:aSound as URL)
    audioPlayer!.numberOfLoops = -1
    audioPlayer!.prepareToPlay()
    audioPlayer!.play()
}
catch {
    print("Cannot play the file")
}

} .............将此代码添加到视图控制器.......

import AVFoundation  **//import at the top**

var player: AVAudioPlayer?  **//declare in code**

MusicHelper.sharedHelper.playBackgroundMusic() **//paste in viewDidLoad