Play and repeat a background sound in XCODE Swift

Firstly import your sound files into your project.

Screen Shot 2015-02-06 at 2.23.19 am

then write following code into AppDelegate.swift. note to repeat your your music, add audioPlayer.numberOfLoops=-1;

import UIKit
import AVFoundation

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
var audioPlayer = AVAudioPlayer()

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(“bgmusic”, ofType: “mp3”)!)

var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)

return true


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s