ios 无需导入自己的声音即可播放系统声音
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7831671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Playing system sound without importing your own
提问by Oksana
Is it possible to play already existing system sounds without importing your own?
是否可以在不导入您自己的声音的情况下播放现有的系统声音?
采纳答案by Krishnabhadra
This code plays apple system sound "Tock.aiff"..I believe you can play different system sounds using this
此代码播放苹果系统声音“Tock.aiff”..我相信您可以使用它播放不同的系统声音
NSString *path = [[NSBundle bundleWithIdentifier:@"com.apple.UIKit"] pathForResource:@"Tock" ofType:@"aiff"];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundID);
AudioServicesPlaySystemSound(soundID);
AudioServicesDisposeSystemSoundID(soundID);
See thisthread
看到这个线程
Apple's documentation on System sounds
Apple 关于系统声音的文档
https://developer.apple.com/documentation/audiotoolbox/system_sound_services
https://developer.apple.com/documentation/audiotoolbox/system_sound_services
回答by yannc2021
I find this list of systemSoundID very useful for accessing the sound ID directly.
http://iphonedevwiki.net/index.php/AudioServices
我发现这个 systemSoundID 列表对于直接访问声音 ID 非常有用。
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.
您还需要在项目中添加 AudioToolbox 框架,并将其添加#include <AudioToolbox.h>
到 .m 或 .h 文件中。
回答by Matheus Veloza
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.
您可以在此处查看完整列表。
回答by TUNER88
List of all system sounds: iOSSystemSoundsLibrary
所有系统声音列表:iOSSystemSoundsLibrary
After you import AVKit
, you can play all this sounds with:
在你之后import AVKit
,你可以播放所有这些声音:
AudioServicesPlaySystemSound (systemSoundID);
回答by Sruit A.Suk
adapted from @yannc2021
改编自@yannc2021
http://iphonedevwiki.net/index.php/AudioServices
http://iphonedevwiki.net/index.php/AudioServices
if you want to use system sound in Swift
如果你想在 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)
回答by Hyman
Swift 4 +
斯威夫特 4 +
NOTE: Try on real device only:
注意:仅在真实设备上试用:
import AVKit
AudioServicesPlaySystemSound(1007);
Or you can try with URL as -
或者您可以尝试使用 URL 作为 -
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
https://github.com/klaas/SwiftySystemSounds/blob/master/README.md
回答by Despotovic
For swift, you can have a look at complete list of system sounds and ringtonesexample.
对于swift,您可以查看完整的系统声音和铃声示例列表。
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
:
哪里model.audioPlayer
只是一个实例AVAudioPlayer
:
///Audio player responsible for playing sound files.
var audioPlayer: AVAudioPlayer = AVAudioPlayer()
回答by carmin
This cocoa-only solution uses existing audio files to play sounds. This method can be used to play any sound file. AVFoundation.framework will have to be added to your frameworks. You will have to define or remove the macros I use which are self explanatory.
这种纯可可解决方案使用现有的音频文件来播放声音。此方法可用于播放任何声音文件。必须将 AVFoundation.framework 添加到您的框架中。您必须定义或删除我使用的不言自明的宏。
I added a category to AVAudioPlayer as follows:
我向 AVAudioPlayer 添加了一个类别,如下所示:
AVAudioPlayer+.h
AVAudioPlayer+.h
#import <AVFoundation/AVAudioPlayer.h>
@interface AVAudioPlayer ( CapSpecs )
+ (AVAudioPlayer*) click;
+ (AVAudioPlayer*) tink;
+ (AVAudioPlayer*) tock;
+ (AVAudioPlayer*) withResourceName: (NSString*) aName;
@end
AVAudioPlayer+.m
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
回答by alecnash
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
@Krishnabhadra 的实施