I´ve already made an app but now I want to play background audio in my app when it launch with endless loop. I know it´s a dumb question but I would be happy if anybody can help me. Thanks in advance. :)
Asked
Active
Viewed 998 times
0
-
Possible duplicate of [How to Play Audio in Background Swift?](http://stackoverflow.com/questions/30280519/how-to-play-audio-in-background-swift) – Leo Dabus Mar 14 '16 at 23:00
1 Answers
0
This is a broad question, but here is one example of what you can do.
Make sure you, above your class declaration, import the AVFoundation
framework, like so:
import AVFoundation
If you have a .mp3
file and you want to play it and loop it endlessly, you can use the following code to do so:
var audioPlayer = AVAudioPlayer()
func startAudio() {
let filePath = NSBundle.mainBundle().pathForResource("fileName", ofType: "mp3")
let fileURL = NSURL.fileURLWithPath(filePath!)
do {
audioPlayer = try AVAudioPlayer.init(contentsOfURL: fileURL, fileTypeHint: AVFileTypeMPEGLayer3)
audioPlayer.numberOfLoops = -1
audioPlayer.volume = 1
} catch {
self.presentViewController(UIAlertController.init(title: "Error", message: "Error Message", preferredStyle: .Alert), animated: true, completion: nil)
}
audioPlayer.play()
}
Call this function wherever you want in your controller and the audio should start playing. Hope this helps.

dokun1
- 2,120
- 19
- 37
-
It works when I want to run it,thank you, but it is no volume this mean I can´t hear anything, I already type at the volume section at 100 – Jojo01 Mar 15 '16 at 15:03
-
The volume should be a floating point number between 0 and 1. Try setting it to `0.85` and see what happens please. – dokun1 Mar 15 '16 at 15:35
-
No, I'm sorry but it's still mute. I would be very happy if you can help me one more time. Thanks in advance – Jojo01 Mar 15 '16 at 16:44