How to Play a Sound Using Swift

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 in assets.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)
}

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)
}
}

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

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)
}


Related Topics



Leave a reply



Submit