Play system sound in iOS 13
This worked:
AudioServicesPlaySystemSound(SystemSoundID(1104))
The list of all system sounds is available here: https://github.com/TUNER88/iOSSystemSoundsLibrary
How Can I Get A List of Available System Sounds in iOS?
Reading up on this, you can find code to get a list of system sound files - but only on a "jail break" device.
Based on this note on Apple's docs (link), it sounds like (sorry for the pun) we won't have much luck in trying to access the "internal" sound clips:
Note System-supplied alert sounds and system-supplied user-interface sound effects are not available to your iOS application. For example, using the kSystemSoundID_UserPreferredAlert constant as a parameter to the AudioServicesPlayAlertSound function will not play anything.
Playing system sound without importing your own
This code plays apple system sound "Tock.aiff"..I believe you can play different system sounds using this
NSString *path = [[NSBundle bundleWithIdentifier:@"com.apple.UIKit"] pathForResource:@"Tock" ofType:@"aiff"];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundID);
AudioServicesPlaySystemSound(soundID);
AudioServicesDisposeSystemSoundID(soundID);
See this thread
Apple's documentation on System sounds
https://developer.apple.com/documentation/audiotoolbox/system_sound_services
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
Playing system sounds using Swift
I believe the correct way is to use the filetype in the third parameter:
var soundID: SystemSoundID = 0
var mainBundle: CFBundleRef = CFBundleGetMainBundle()
if let ref: CFURLRef = CFBundleCopyResourceURL(mainBundle, CFSTR("roar"), CFSTR("aif"), nil) {
println("Here is your ref: \(ref)")
AudioServicesCreateSystemSoundID(ref, &soundID)
AudioServicesPlaySystemSound(soundID)
} else {
println("Could not find sound file")
}
Are you sure the file is roar.aif and not roar.aiff?
Make sure the file is not in a subdirectory, if so you have to add this as a fourth parameter.
See: https://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFBundleRef/index.html#//apple_ref/c/func/CFBundleCopyResourceURL
Related Topics
When Do I Need to Call Setneedsdisplay in iOS
Uibutton Touch Is Delayed When in Uiscrollview
Swift Modal View Controller with Transparent Background
How to Open Maps App Programmatically with Coordinates in Swift
iOS Convert Large Numbers to Smaller Format
Xcode 6 with Swift Super Slow Typing and Autocompletion
Uiscrollview with Centered Uiimageview, Like Photos App
Add Shadow on Uiview Using Swift 3
Build Not Visible in Itunes Connect
Convert Uiimage to Nsdata and Convert Back to Uiimage in Swift
How to Change the Color of the Text in a Uipickerview Under iOS 7
When Should Translatesautoresizingmaskintoconstraints Be Set to True
What Size Should Tabbar Images Be
Iphone:How to Detect the End of Slider Drag
Swift - How to Dismiss All of View Controllers to Go Back to Root
Coredata Get Distinct Values of Attribute
Format Uilabel with Bullet Points
Navigation Bar Under Status Bar After Video Playback in Landscape Mode