How to play a sound in Swift 5 - swift

I am new at swift and Xcode, and When I am trying to play a sound, it gives me an error that I have no idea what is wrong.
This is the code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func buttonC(_sender: UIButton) {
playSound()
}
func playSound() {
guard let path = Bundle.main.path(forResource: "C", ofType:"wav") else {
return }
let url = URL(fileURLWithPath: path)
do {
player = try AVAudioPlayer(contentsOf: url)
player?.play()
} catch let error {
print(error.localizedDescription)
}
}
}
And this is the error:
I will appreciate the help; thanks!

Probably you have renamed your IBAction method name, now it's different and it's connected to the previous name inside your storyboard.
Disconnect your action method and reconnect it appropriately.
Go to your storyboard, select button and then in connectionInspector (cmd + option + 6) delete your previous connection.
Then link your button to the #IBAction function correctly.
I hope it helps you

Related

How can I start and stop audio with the same UI button? – Swift

I am making a very simple IOS app. It is a button, and when pressed a long .wav file plays. I would love to be able to press the button again, and the audio would stop playing. I’ve tried many of the solutions here as there are similar questions, but I’m stuck. Any ideas?
import UIKit
import AVFoundation
class ViewController: UIViewController {
// Making a variable called player. It is the AVAudioPlayer
var player: AVAudioPlayer!
// No idea what this is.
override func viewDidLoad() {
super.viewDidLoad()
}
//This is the key pressed. Inside is the playSound and a print for checking
#IBAction func keyPressed(_ sender: UIButton) {
playSound()
print("button pressed")
}
//Turn playSound into a func – and tell it what to play and play it if button is pressed
func playSound() {
let url = Bundle.main.url(forResource: "audio", withExtension: "wav")
player = try! AVAudioPlayer(contentsOf: url!)
player.play()
}
}
AVAudioPlayer has the isPlaying (docs) property that you can check to determine if you should play or stop playback when your button is pressed.
import AVFoundation
import UIKit
class ViewController: UIViewController {
// Making a variable called player. It is the AVAudioPlayer
var player: AVAudioPlayer!
// This is the key pressed. Inside is the playSound and a print for checking
#IBAction func keyPressed(_ sender: UIButton) {
if player.isPlaying {
stopSound()
} else {
playSound()
}
}
// Turn playSound into a func – and tell it what to play and play it if button is pressed
func playSound() {
let url = Bundle.main.url(forResource: "audio", withExtension: "wav")
player = try! AVAudioPlayer(contentsOf: url!)
player.play()
}
func stopSound() {
player.stop()
}
}
Sidenote: The viewDidLoad method override isn't needed unless you're wanting to have custom code run when the view is loaded by the system.

Adding Audio Controls in iOS App using Swift in Xcode

I have added background music to my app using the following code:-
Now I am trying to add audio controls to my app using the following methods, but after I click on another view controller and come back to the main view controller the play button is not working. Any help will be highly appreciated Thanks!
var toggleState = 1
var music: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
playMusic()
}
func playMusic() {
if let musicURL = Bundle.main.url(forResource: "Adding", withExtension: "mp3") {
if let audioPlayer = try? AVAudioPlayer(contentsOf: musicURL) {
music = audioPlayer
music.numberOfLoops = -1
music.play()
}
}
}
#IBAction func playButtonPressed(_ sender: Any) {
if (toggleState == 1) {
music.pause()
toggleState = 2
}
else {
music.play()
toggleState = 1
}
}

Swift play sound works in simulator but not IPhone

I wrote the following code that plays a sound when a button is pressed, it works perfectly on the simulator (IPhone7), but not when running on my IPhone X. The mute button is not on on my phone.
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate{
var soundPlayer : AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func notePressed(_ sender: UIButton) {
playNote(noteIndex: sender.tag)
}
func playNote(noteIndex : Int){
let soundURL = Bundle.main.url(forResource: "note\(noteIndex)", withExtension: "wav")
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options:[])
try AVAudioSession.sharedInstance().setActive(true)
soundPlayer = try AVAudioPlayer(contentsOf:soundURL!)
} catch {
print (error)
}
soundPlayer.play()
}
}
I finally found out the solution:
Go to: File->Project Settings... , change "Derived Data:" to "Project-relative Location", click "Done".
That worked for me.

Swift AVAudioplayer on Button press

I am trying to have a button that will play a sound when pushed.
The app I have has 6 buttons (with 6 different sounds). I only have one listed because I am trying to get one button to work correctly before doing the rest. I know the button is working (from the print command at the bottom), but it is not playing the sound.
import UIKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var player : AVAudioPlayer?
#IBAction func buttonOne(_ sender: Any) {
func playSound() {
let url = Bundle.main.url(forResource: "drinking", withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOf: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error as NSError {
print(error.description)
}
}
print("Anakin: IT IS WORKING!")
}
}
Is it printing any error?
Can you try doing this?
let path = Bundle.main.path(forResource: "FILE NAME WITH EXTENSION", ofType:nil)!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
sound.play()
} catch {
// couldn't load file :(
}

Play Sound Using AVFoundation with Swift 2

I am trying to play a sound in my iOS app (written in Swift 2) using AVFoundation. I had it working with no issues with the previous version of Swift. I am using Xcode 7.0. I am not sure what the issue is and cannot find any additional info for Swift 2 regarding playing sounds. Here's my code for the sound part:
import AVFoundation
class ViewController: UIViewController {
var mySound = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
mySound = self.setupAudioPlayerWithFile("mySound", type:"wav")
mySound.play()
}
func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer {
var path = NSBundle.mainBundle().pathForResource(file, ofType:type)
var url = NSURL.fileURLWithPath(path!)
var error: NSError?
var audioPlayer:AVAudioPlayer?
audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
return audioPlayer!
}
}
I am getting this error but have a feeling there maybe some other issue:
'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?
Like Leo said
You need to implement do try catch error handling.
Here is another example of some code that will run sound when a button is pressed.
import UIKit
import AVFoundation
class ViewController: UIViewController {
#IBAction func play(sender: AnyObject) {
player.play()
}
#IBAction func pause(sender: AnyObject) {
player.pause()
}
var player: AVAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
let audioPath = NSBundle.mainBundle().pathForResource("sound", ofType: "mp3")!
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
} catch {
// Process error here
}
}
}
I hope this helps!
You need to implement do try catch error handling. Try like this:
func setupAudioPlayerWithFile(file: String, type: String) -> AVAudioPlayer? {
if let url = NSBundle.mainBundle().URLForResource(file, withExtension: type) {
do {
return try AVAudioPlayer(contentsOfURL: url)
} catch let error as NSError {
print(error.localizedDescription)
}
}
return nil
}