-9

My sound file name is : bensound-november.mp3 and I want to play an infinite this file.

I use blow code. please suggest simple code fit with this code.

import UIKit
import AVFoundation

class ViewController: UIViewController {






override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}
}
Kyu
  • 139
  • 2
  • 13

2 Answers2

2

not sure if it has to be in .wav format or not, but i have some code for this give me a sec.

//EDIT

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var AudioPlayer = AVAudioPlayer()




    override func viewDidLoad() {
        super.viewDidLoad()
        let AssortedMusics = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("bensound-november", ofType: "mp3")!)
        AudioPlayer = try! AVAudioPlayer(contentsOfURL: AssortedMusics)
        AudioPlayer.prepareToPlay()
        AudioPlayer.numberOfLoops = -1
        AudioPlayer.play()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

that should work, and it should be looped aswell, since if make number of loops = -1, thats the effect it has for some reason i don't understand, so i won't explain it.

hope that helps!

Bucket
  • 56
  • 5
  • Perhaps you should move this code to `-application:didFinishLaunchingWithOptions:`, or better, some other persistent object (a singleton?). Depending on the navigation structure of the app, the player will be deallocated as soon as the hosting view controller is. – Nicolas Miari Dec 28 '15 at 07:50
0

Just giving an updated version of Bucket's answer. Thanks.

import AVFoundation

    override func viewDidLoad() {
        super.viewDidLoad()

        let AssortedMusics = NSURL(fileURLWithPath: Bundle.main.path(forResource: "audioBg", ofType: "mp3")!)
        AudioPlayer = try! AVAudioPlayer(contentsOf: AssortedMusics as URL)
        AudioPlayer.prepareToPlay()
        AudioPlayer.numberOfLoops = -1
        AudioPlayer.play()
    }
KiritoLyn
  • 626
  • 1
  • 10
  • 26