-1

I don't know how add background music for my app(game) in Swift. When I'm run it, background music must be played. A few years ago I worked in Xcode, but now it changed, and that's a crap. My app without music. In internet searching I didn't found the answer. Most of all answers connect music playing when you push the button (I don't need it), I need to play music at background when my app is running.

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

0

Use the 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()

import AvFoundation !!!!

Korpel
  • 2,432
  • 20
  • 30
0

Swift 4.2 Update **** Make a new class and Paste this code:...........****

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")
}

} .............add this code to view controller................

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

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

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