How to play iOS built-in Sounds in your App
ShowNote presents an object with effects, including a sound effect.
UISounds
I utilized a device built-in sound file for this effect, and, naturally, the sound files are located in the UISounds directory:
let soundsRoot = URL(fileURLWithPath: "/System/Library/Audio/UISounds")
To list sounds, I retrieved all files from UISounds using contentsOfDirectory
. Here are the details from the article:
let files = try! FileManager.default
.contentsOfDirectory(at: soundsRoot,
includingPropertiesForKeys: nil,
options: [.skipsSubdirectoryDescendants,
.skipsPackageDescendants,
.skipsHiddenFiles])
However, my example app encountered an error stating,
Upon investigation, I observed the contents of /System/Library/Audio
instead of UISounds.
There is no UISounds directory. So, I checked the path on my Macbook, and I saw a list exactly the same as in the simulator. Yes, when I accessed the root path from the Simulator, the Macbook’s root path was returned instead of the Simulator’s. This is because the Simulator doesn’t have its own disk.
Real Device
Therefore, I ran the example on my iPhone, and I could see the sound files.
Play
To play an audio file, we need a player. In this case, I used AVAudioPlayer
, which is part of AVFoundation
. So, you should import it first.
import AVFoundation
var player: AVAudioPlayer?
Usage is very easy. Initialize it with the URL of the sound file and play it.
player = try .init(contentsOf: selectedSound)
player?.play()
If you try to initialize the player with a directory, it will raise an error. To exclude directories, I used an extension to determine if the URL is a directory.
extension URL{
func isDirectory() -> Bool{
var is_dir : ObjCBool = ObjCBool.init(false);
FileManager.default.fileExists(atPath: self.path, isDirectory: &is_dir);
return is_dir.boolValue;
}
}
And I filtered the children of UISounds.
let files = ...filter{ !$0.isDirectory }
The full source is in this example repository.
If you found this post helpful, please give it a round of applause 👏. Explore more iOS-related content in my other posts.
For additional insights and updates, check out my LinkedIn profile. Thank you for your support!
Troubleshootings
The file “UISounds” couldn’t be opened because there is no such file.
Run in Real Device.
References
https://www.theiphonewiki.com/wiki//System/Library/Audio/UISounds