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.
Asked
Active
Viewed 1,953 times
-1
-
see this link may be help with you http://stackoverflow.com/questions/31422014/play-background-music-in-app – Anbu.Karthik Sep 08 '15 at 06:42
2 Answers
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
-
AVFoundation added. But where to insert the code in ViewController.swift? In what place paste it that would be without errors? – John Rambo Sep 08 '15 at 07:06
-
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

Shahriar Kabir Khan
- 647
- 8
- 17
-
Please find more ogranized code in here --> https://stackoverflow.com/questions/31422014/play-background-music-in-app/54028858#54028858 – Shahriar Kabir Khan Jul 19 '19 at 10:35