Skip to content

Playing music with Swift

   

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.

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()
}
}
view raw PlayMusic.swift hosted with ❤ by GitHub

  1. Array(Ruby)
  2. Whitening the UIStatusBar
  3. UITableView and UISearchBar
  4. UserNotification(LocalNotification)
  5. Speech Recognition(SFSpeechRecognizer)
  6. UITextField
  7. Creating a CAF file