Playing system sound without importing your own

后端 未结 10 2118
情深已故
情深已故 2020-11-27 02:26

Is it possible to play already existing system sounds without importing your own?

相关标签:
10条回答
  • 2020-11-27 03:03

    You can use this for all default system audio.

    Example, for the tap sound user this:

    AudioServicesPlaySystemSound(1104);
    

    For positive sounds, use this:

     AudioServicesPlaySystemSound(1054);
    

    And, negative sounds use this:

     AudioServicesPlaySystemSound(1053);
    

    The complete list you can see here.

    0 讨论(0)
  • 2020-11-27 03:11

    For Swift

    import AVFoundation
    
    func play(sound: String) {
            var soundID: SystemSoundID = SystemSoundID()
            let mainBundle = CFBundleGetMainBundle()
            if let ref = CFBundleCopyResourceURL(mainBundle, sound as CFString, nil, nil) {
                AudioServicesCreateSystemSoundID(ref, &soundID);
                AudioServicesPlaySystemSound(soundID);
            }
    }
    

    the implementation of @Krishnabhadra

    0 讨论(0)
  • 2020-11-27 03:11

    This should play most macOS system sounds

    #include <AudioToolbox/AudioToolbox.h>
    
    
    for (int i = 0; i < 50; i++) {
        NSLog(@"playing %i", i);
        AudioServicesPlaySystemSound (i);
        [NSThread sleepForTimeInterval:1.0];
    }
    
    
    0 讨论(0)
  • 2020-11-27 03:12

    For swift, you can have a look at complete list of system sounds and ringtones example.

    Edit: Ok, here are the most important peaces of code from this example:

        ///The directories where sound files are located.
        let rootSoundDirectories: [String] = ["/Library/Ringtones", "/System/Library/Audio/UISounds"]
    
        ///Array to hold directories when we find them.
        var directories: [String] = []
    
        ///Tuple to hold directories and an array of file names within.
        var soundFiles: [(directory: String, files: [String])] = []
    
        //Starting with the "/Library/Ringtones" & "/System/Library/Audio/UISounds" directories, it looks for other sub-directories just one level lower and saves their relative path in directories array.
        //- URLs: All of the contents of the directory (files and sub-directories).
        func getDirectories() {
            let fileManager: NSFileManager = NSFileManager()
            for directory in rootSoundDirectories {
                let directoryURL: NSURL = NSURL(fileURLWithPath: "\(directory)", isDirectory: true)
    
                do {
                    if let URLs: [NSURL] = try fileManager.contentsOfDirectoryAtURL(directoryURL, includingPropertiesForKeys: [NSURLIsDirectoryKey], options: NSDirectoryEnumerationOptions()) {
                        var urlIsaDirectory: ObjCBool = ObjCBool(false)
                        for url in URLs {
                            if fileManager.fileExistsAtPath(url.path!, isDirectory: &urlIsaDirectory) {
                                if urlIsaDirectory {
                                    let directory: String = "\(url.relativePath!)"
                                    let files: [String] = []
                                    let newSoundFile: (directory: String, files: [String]) = (directory, files)
                                    directories.append("\(directory)")
                                    soundFiles.append(newSoundFile)
                                }
                            }
                        }
                    }
                } catch {
                    debugPrint("\(error)")
                }
            }
        }
    
        //For each directory, it looks at each item (file or directory) and only appends the sound files to the soundfiles[i]files array.
        //- URLs: All of the contents of the directory (files and sub-directories).
            func loadSoundFiles() {
                for i in 0...directories.count-1 {
                    let fileManager: NSFileManager = NSFileManager()
                    let directoryURL: NSURL = NSURL(fileURLWithPath: directories[i], isDirectory: true)
    
                    do {
                        if let URLs: [NSURL] = try fileManager.contentsOfDirectoryAtURL(directoryURL, includingPropertiesForKeys: [NSURLIsDirectoryKey], options: NSDirectoryEnumerationOptions()) {
                            var urlIsaDirectory: ObjCBool = ObjCBool(false)
                            for url in URLs {
                                if fileManager.fileExistsAtPath(url.path!, isDirectory: &urlIsaDirectory) {
                                    if !urlIsaDirectory {
                                        soundFiles[i].files.append("\(url.lastPathComponent!)")
                                    }
                                }
                            }
                        }
                    } catch {
                        debugPrint("\(error)")
                    }
                }
            }
    

    The example shows the system sound files in a table view. Sounds are played as shown in this function:

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
            //Play the sound
            let directory: String = soundFiles[indexPath.section].directory
            let fileName: String = soundFiles[indexPath.section].files[indexPath.row]
            let fileURL: NSURL = NSURL(fileURLWithPath: "\(directory)/\(fileName)")
            do {
                model.audioPlayer = try AVAudioPlayer(contentsOfURL: fileURL)
                model.audioPlayer.play()
            } catch {
                debugPrint("\(error)")
            }
        }
    

    Where model.audioPlayer is just an instance of AVAudioPlayer:

    ///Audio player responsible for playing sound files.
    var audioPlayer: AVAudioPlayer = AVAudioPlayer()
    
    0 讨论(0)
  • 2020-11-27 03:13

    Swift 4 +

    NOTE: Try on real device only:

    import AVKit
    AudioServicesPlaySystemSound(1007);
    

    Or you can try with URL as -

    let url = URL(fileURLWithPath: "/System/Library/Audio/UISounds/payment_success.caf")
    var soundID: SystemSoundID = 0
    AudioServicesCreateSystemSoundID(url as CFURL, &soundID)
    AudioServicesPlaySystemSound(soundID);
    

    https://github.com/klaas/SwiftySystemSounds/blob/master/README.md

    0 讨论(0)
  • 2020-11-27 03:23

    I find this list of systemSoundID very useful for accessing the sound ID directly.
    http://iphonedevwiki.net/index.php/AudioServices

    For example, to play a key press tock sound.

    #define systemSoundID    1104
    AudioServicesPlaySystemSound (systemSoundID);
    

    You'll also need to add the AudioToolbox framework in your project, and add #include <AudioToolbox.h> to your .m or .h file.

    0 讨论(0)
提交回复
热议问题