This is a sample code to play music easily with Swift. Repeat playback was easy to do. It's not in the sample code, but it should handle errors properly.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import AVFoundation | |
class ViewController: UIViewController { | |
var audioPlayer : AVAudioPlayer! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
let soundFilePath : String = Bundle.main.path(forResource: "BGM_a", ofType: "mp3")! | |
let fileURL : URL = URL(fileURLWithPath: soundFilePath) | |
do{ | |
audioPlayer = try AVAudioPlayer(contentsOf: fileURL) | |
} | |
catch{ | |
} | |
//numberOfLoopsに-1を指定すると無限ループする。 | |
audioPlayer.numberOfLoops = -1 | |
audioPlayer.play() | |
} | |
} | |