Creating and playing a sound in swift
Here's a bit of code I've got added to FlappySwift that works:
import SpriteKit
import AVFoundation
class GameScene: SKScene {
// Grab the path, make sure to add it to your project!
var coinSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "coin", ofType: "wav")!)
var audioPlayer = AVAudioPlayer()
// Initial setup
override func didMoveToView(view: SKView) {
audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil)
audioPlayer.prepareToPlay()
}
// Trigger the sound effect when the player grabs the coin
func didBeginContact(contact: SKPhysicsContact!) {
audioPlayer.play()
}
}
How to play a sound using Swift?
Most preferably you might want to use AVFoundation.
It provides all the essentials for working with audiovisual media.
Update: Compatible with Swift 2, Swift 3 and Swift 4 as suggested by some of you in the comments.
Swift 2.3
import AVFoundation
var player: AVAudioPlayer?
func playSound() {
let url = NSBundle.mainBundle().URLForResource("soundName", withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOfURL: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error as NSError {
print(error.description)
}
}
Swift 3
import AVFoundation
var player: AVAudioPlayer?
func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
let player = try AVAudioPlayer(contentsOf: url)
player.play()
} catch let error {
print(error.localizedDescription)
}
}
Swift 4 (iOS 13 compatible)
import AVFoundation
var player: AVAudioPlayer?
func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
/* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
Make sure to change the name of your tune as well as the extension.
The file needs to be properly imported (Project Build Phases
>Copy Bundle Resources
). You might want to place it inassets.xcassets
for
greater convenience.
For short sound files you might want to go for non-compressed audio formats such as .wav
since they have the best quality and a low cpu impact. The higher disk-space consumption should not be a big deal for short sound files. The longer the files are, you might want to go for a compressed format such as .mp3
etc. pp. Check the compatible audio formats of CoreAudio
.
Fun-fact: There are neat little libraries which make playing sounds even easier. :)
For example: SwiftySound
How can I play a sound in swift without stopping the playing music?
Set your AVAudioSession
to .duckOthers
or .mixWithOthers
:
(Before you play sounds):
do {
try AVAudioSession.sharedInstance()
.setCategory(.playback, options: .duckOthers)
try AVAudioSession.sharedInstance()
.setActive(true)
} catch {
print(error)
}
Play a sound file on repeat in Swift?
By default AVAudioPlayer plays its audio from start to finish then stops, but we can control how many times to make it loop by setting its numberOfLoops property. For example, to make your audio play three times in total, you’d write this:
player.numberOfLoops = 3
if you want the infinite loop then use
player.numberOfLoops = -1
for e.g
func playSound(soundName: String) { //
let url = Bundle.main.url(forResource: soundName, withExtension: "wav")
player = try! AVAudioPlayer(contentsOf: url!)
player.numberOfLoops = -1 // set your count here
player.play()
} // End of Play Sound
How to play a sound on iOS 11 with swift 4? And where i place The mp3 file?
SWIFT 4 / XCODE 9.1
import AVFoundation
var objPlayer: AVAudioPlayer?
func playAudioFile() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
// For iOS 11
objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
// For iOS versions < 11
objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3)
guard let aPlayer = objPlayer else { return }
aPlayer.play()
} catch let error {
print(error.localizedDescription)
}
}
How to make a function play different sounds in Swift
do like
@objc func yourbtnActionName(_ sender : UIButton){
switch sender.tag {
case 1:
commonSoundCode(name: "sound1")
break
case 2:
commonSoundCode(name: "yoursecondSoundname")
break
default:
break
}
}
then common method as
func commonSoundCode(name: String){
let path = Bundle.main.path(forResource: name, ofType: "wav")!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
myAudio = sound
sound.play()
} catch {
//
}
}
option 2
if your sound files are in the same sequence, for e.g (sound1.wav, sound2.wav......, sound10.wav) then call like
@objc func yourbtnActionName(_ sender : UIButton){
let path = Bundle.main.path(forResource: "sound\(sender.tag)", ofType: "wav")!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
myAudio = sound
sound.play()
} catch {
//
}
}
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
}
}
}
Related Topics
Table View Images Never Being Released
Xcode Canvas for Swiftui Previews Does Not Show Up
Nstimer Timerwithtimeinterval: Not Working
Generate Random Numbers with a Given Distribution
Sharing Code Between Original iOS App and App Extension
Uistackview Distribution Fill Equally
Creating Delegates on the Spot with Blocks
iOS How to Detect When App Was Removed from Process
How to Get the Udid in iOS 6 and iOS 7
Run Timer in 'Background' When App Is Closed
How to Save a Uicolor with Userdefaults
Custom Rounding Corners on Uiview
Storing Asynchronous Cloud Firestore Query Results in Swift
What Should Xcode 6 Gitignore File Include
Ios9 - This Application Is Modifying the Autolayout Engine from a Background Thread -- Where