iphone objective-c ios

iphone - Reproducción de sonido del sistema sin importar su propio sonido



objective-c ios (9)

Encuentro esta lista de systemSoundID muy útil para acceder a la ID de sonido directamente.
http://iphonedevwiki.net/index.php/AudioServices

Por ejemplo, para presionar una tecla, toque el sonido.

#define systemSoundID 1104 AudioServicesPlaySystemSound (systemSoundID);

También deberá agregar el marco de AudioToolbox en su proyecto y agregar #include <AudioToolbox.h> a su archivo .m o .h.

¿Es posible reproducir los sonidos del sistema ya existentes sin importar el suyo?


Esta solución solo de cacao usa archivos de audio existentes para reproducir sonidos. Este método se puede usar para reproducir cualquier archivo de sonido. AVFoundation.framework deberá agregarse a sus frameworks. Deberá definir o eliminar las macros que uso que se explican por sí mismas.

Agregué una categoría a AVAudioPlayer de la siguiente manera:

AVAudioPlayer + .h

#import <AVFoundation/AVAudioPlayer.h> @interface AVAudioPlayer ( CapSpecs ) + (AVAudioPlayer*) click; + (AVAudioPlayer*) tink; + (AVAudioPlayer*) tock; + (AVAudioPlayer*) withResourceName: (NSString*) aName; @end

AVAudioPlayer + .m

#import "AVAudioPlayer+.h" @implementation AVAudioPlayer ( CapSpecs ) + (AVAudioPlayer*) click { StaticReturn ( [AVAudioPlayer withResourceName: @"iPod Click"] ); } + (AVAudioPlayer*) tink { StaticReturn ( [AVAudioPlayer withResourceName: @"Tink"] ); } + (AVAudioPlayer*) tock { StaticReturn ( [AVAudioPlayer withResourceName: @"Tock"] ); } + (AVAudioPlayer*) withResourceName: (NSString*) aName { NSBundle* zBundle = [NSBundle bundleWithIdentifier: @"com.apple.UIKit"]; NSURL* zURL = [zBundle URLForResource: aName withExtension: @"aiff"]; (void) RaiseIfNil ( nil, zURL, ([SWF @"URL for %@",aName]) ); NSError* zError = nil; AVAudioPlayer* zAudio = [[AVAudioPlayer alloc] initWithContentsOfURL: zURL error: &zError]; RaiseError ( nil, zError, @"AVAudioPlayer init error" ); #ifdef DEBUG // Apple records the console dump which occurs as a bug in the iOS simulator // all of the following commented code causes the BS console dump to be hidden int zOldConsole = dup(STDERR_FILENO); // record the old console freopen("/dev/null", "a+", stderr); // send console output to nowhere (void)[zAudio prepareToPlay]; // create the BS dump fflush(stderr); // flush the console output dup2(zOldConsole, STDERR_FILENO); // restore the console output #endif return zAudio; } @end


Este código reproduce el sonido del sistema de Apple "Tock.aiff" ... Creo que puedes tocar diferentes sonidos del sistema usando este

NSString *path = [[NSBundle bundleWithIdentifier:@"com.apple.UIKit"] pathForResource:@"Tock" ofType:@"aiff"]; SystemSoundID soundID; AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundID); AudioServicesPlaySystemSound(soundID); AudioServicesDisposeSystemSoundID(soundID);

Ver this hilo

La documentación de Apple sobre los sonidos del sistema

https://developer.apple.com/documentation/audiotoolbox/system_sound_services



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

la implementación de @Krishnabhadra


Para información rápida , puede echar un vistazo a la github.com/CQH/iOS-Sounds-and-Ringtones ejemplo de github.com/CQH/iOS-Sounds-and-Ringtones .

Editar: Ok, aquí están las paces más importantes de código de este ejemplo:

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

El ejemplo muestra los archivos de sonido del sistema en una vista de tabla. Los sonidos se reproducen como se muestra en esta función:

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

Donde model.audioPlayer es solo una instancia de AVAudioPlayer :

///Audio player responsible for playing sound files. var audioPlayer: AVAudioPlayer = AVAudioPlayer()


Puede usar esto para todo el audio del sistema predeterminado.

Ejemplo, para el usuario de sonido de toque esto:

AudioServicesPlaySystemSound(1104);

Para sonidos positivos, usa esto:

AudioServicesPlaySystemSound(1054);

Y, los sonidos negativos usan esto:

AudioServicesPlaySystemSound(1053);

La lista completa que puedes ver github.com/TUNER88/iOSSystemSoundsLibrary .


adaptado de @ yannc2021

http://iphonedevwiki.net/index.php/AudioServices

si quieres usar el sonido del sistema en Swift

// import this import AVFoundation // add this method required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // declared system sound here let systemSoundID: SystemSoundID = 1104 // to play sound AudioServicesPlaySystemSound (systemSoundID)


Swift 4 +

NOTA: prueba solo en el dispositivo real:

import AVKit AudioServicesPlaySystemSound(1007);

O puede probar con la URL como -

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