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

@UIApplicationMain
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”)!)
println(alertSound)

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

return true
}

Advertisement

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s