This time, I will explain how to make a sound with the app. Recently I made an original application with rails, so I am studying mainly on swift.
ViewController.swift
import AVFoundation
//Need the above description
class calcViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
First, we will introduce a framework for producing sound with import AVFoundation. In addition to this framework, there are many frameworks released by Apple Inc., so please introduce them according to what you want to make. Here is a list of frameworks. http://iosdev.app-rox.com/framework/
Next, let's put the music in the file. Please make it .mp3 in advance. Then put it in the file you are making in xcode. This time, the music to be put in the file will be tentatively named "correct.mp3" and "incorrect.mp3".
ViewController.swift
var player:AVAudioPlayer?
func playSound(name:String){
let path = Bundle.main.bundleURL.appendingPathComponent(name + ".mp3")
do {
player = try AVAudioPlayer(contentsOf: path,fileTypeHint: nil)
player?.play()
}catch{
print("error")
}
}
We will instantiate it with var player: AVAudioPlayer? So that it can be used.
let path = Bundle.main.bundleURL.appendingPathComponent(name + ".mp3")
I put information in a constant called path. It is moving to find the imported music file with "Bundle.main.bundleURl" and reading the music file with "appendingPathComponent". The name of (name + ".mp3") takes an argument.
do {} catch {} is called do-catch, and it is a statement that handles exceptions. Call the instance with try and put path in contrastOf.
ViewController.swift
func setbutton{
answer = 1
if answer == 1{
//When answer is 1
playSound(name: "correct")
}else{
//When answer is other than 1
playSound(name: "incorrect")
}
}
Music is played by writing playSound (name: "name of music file"). Did you all do that?
Recommended Posts