how to play an audio file in your iOS App using Xcode 10.1

Опубликовано: 19 Август 2019
на канале: sans-code
183
3

you can paste this code in your view controller:

import UIKit
import AVFoundation

class ViewController: UIViewController {

var audioplayer = AVAudioPlayer()

override func viewDidLoad() {
super.viewDidLoad()
//make sure you change the name of the file if you have saved the audio with a different name
let loc = Bundle.main.url(forResource: "ring", withExtension: ".wav")

do{
try audioplayer = AVAudioPlayer(contentsOf:loc!)
audioplayer.prepareToPlay()
audioplayer.volume = 1.0
}
catch{
print("error")
}
}
//play
@IBAction func playbutton(_ sender: Any) {
audioplayer.play()
}
//make sure that you connect IBAction properties and the buttons when you copy this code
//stop
@IBAction func stopbutton(_ sender: Any) {
audioplayer.stop()
}

}