Swift, How to Play Sound When Press a Button

Swift, how to play sound when press a button

I hope it will help you.

import UIKit
import AVFoundation

class ViewController: UIViewController {
// make sure to add this sound to your project
var pianoSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("C", ofType: "m4a"))
var audioPlayer = AVAudioPlayer()

override func viewDidLoad() {
super.viewDidLoad()

audioPlayer = AVAudioPlayer(contentsOfURL: pianoSound, error: nil)
audioPlayer.prepareToPlay()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

@IBAction func PianoC(sender: AnyObject) {
audioPlayer.play()
}

}

Latest Swift 4.2 :

   let pianoSound = URL(fileURLWithPath: Bundle.main.path(forResource: "btn_click_sound", ofType: "mp3")!)
var audioPlayer = AVAudioPlayer()

@IBAction func PianoC(sender: AnyObject) {
do {
audioPlayer = try AVAudioPlayer(contentsOf: pianoSound)
audioPlayer.play()
} catch {
// couldn't load file :(
}
}

Play specific sound when specific button is pressed in iOS

import UIKit
import AVFoundation

class ViewController: UIViewController {

@IBOutlet weak var playSoundSwitch: UISegmentedControl!

var backgroundMusicPlayer: AVAudioPlayer?

var player:AVAudioPlayer = AVAudioPlayer()

@discardableResult func playSound(named soundName: String) -> AVAudioPlayer {


let audioPath = Bundle.main.path(forResource: soundName, ofType: "wav")
player = try! AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
player.play()
return player
}


@IBAction func catButtonPressed(_ sender: Any) {

if playSoundSwitch.selectedSegmentIndex == 0 {
playSound(named: "catSound")
}


}

@IBAction func dogButtonPressed(_ sender: Any) {
if playSoundSwitch.selectedSegmentIndex == 0 {
playSound(named: "dogSound")
}
}

@IBAction func birdButtonPressed(_ sender: Any) {

if playSoundSwitch.selectedSegmentIndex == 0 {
playSound(named: "birdSound")
print("bird sound")
}
}

@IBAction func playBackgroundMusicSwitchChanged(_ sender: Any) {


if (sender as AnyObject).selectedSegmentIndex == 0 {
backgroundMusicPlayer = playSound(named: "backgroundSound")
} else {
backgroundMusicPlayer?.stop()
backgroundMusicPlayer = nil
}
}

}

Why can't I play sound when a button is pressed?

You are getting the error because the url doesn't exist.

Check whether you specified the correct file name and wrap the play function in do block to catch any other errors. The following code worked without any errors.

func playSound() {
guard let url = Bundle.main.url(forResource: "C", withExtension: "wav") else {
print("File not found")
return
}
do {
player = try AVAudioPlayer(contentsOf: url)
player.play()
} catch {
print(error)
}

}

Play audio on touch down action of button in swiftui

Here is a demo of possible approach. Tested with Xcode 11.4 / iOS 13.4

Note: you should keep reference to AVAudioPlayer while it is playing and better track its state, so this is more appropriate to do in some helper class (like view model)

class PlayViewModel {
private var audioPlayer: AVAudioPlayer!
func play() {
let sound = Bundle.main.path(forResource: "filename", ofType: "wav")
self.audioPlayer = try! AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound!))
self.audioPlayer.play()
}
}

struct DemoPressedButton: View {
let vm = PlayViewModel()

var body: some View {
Button("Demo") {
print(">> tap up")
}
.buttonStyle(PressedButtonStyle {
print(">> tap down")
self.vm.play()
})
}
}

Swift, how to play sound again and again by pressing a button

You have to stop the sound before you can play it again. A good discussion here:

Swift - Have an audio repeat, but it plays in intervals?

Swift 4: How to have a sound play over itself when a button is pushed?

One player can play one sound at a time only. You probably have to do following

Create an array of players

var arrPlayer: [AVAudioPlayer] = []

And then inside your method do the following

let url = Bundle.main.url(forResource: "Bull", withExtension: "mp3")!

do
{
player = try AVAudioPlayer(contentsOf: url)

arrPlayer.append(player)

try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
try AVAudioSession.sharedInstance().setActive(true)

arrPlayer.last?.prepareToPlay()
arrPlayer.last?.play()
}

catch let error
{
print(error.localizedDescription)
}

How to play sound, when backBarButton (from NavigationController) is pressed? (for Swift)

I found a solution in the post sent in the comments. This post

I didn't fully understand, what's exactly happening there (because there was Objective-C code).

So, the solution is to create a custom leftBarButtonItem instead of backBarButtonItem and add this button in every VC in NavigationVC you need this button to be.

Here is code you have to add in every VC:

override func viewDidLoad() {
super.viewDidLoad()

//some other code

self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "backButtonIcon"), style: UIBarButtonItem.Style.plain, target: self, action: #selector(backButtonPressed))
}

@objc func backButtonPressed() {

// implement your action here
}


Related Topics



Leave a reply



Submit