Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Iphone 播放系统声音而不导入您自己的_Iphone_Objective C_Ios - Fatal编程技术网

Iphone 播放系统声音而不导入您自己的

Iphone 播放系统声音而不导入您自己的,iphone,objective-c,ios,Iphone,Objective C,Ios,是否可以在不导入您自己的系统声音的情况下播放现有的系统声音?此代码播放apple系统声音“Tock.aiff”。我相信您可以使用此代码播放不同的系统声音 NSString *path = [[NSBundle bundleWithIdentifier:@"com.apple.UIKit"] pathForResource:@"Tock" ofType:@"aiff"]; SystemSoundID soundID; AudioServi

是否可以在不导入您自己的系统声音的情况下播放现有的系统声音?

此代码播放apple系统声音“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);
见线

苹果关于系统声音的文档

此cocoa only解决方案使用现有音频文件播放声音。 此方法可用于播放任何声音文件。 必须将AVFoundation.framework添加到您的框架中。 您将必须定义或删除我使用的自解释宏

我向AVAudioPlayer添加了一个类别,如下所示:

AVAudioPlayer+.h

 #import <AVFoundation/AVAudioPlayer.h>

@interface AVAudioPlayer ( CapSpecs )
+ (AVAudioPlayer*) click;
+ (AVAudioPlayer*) tink;
+ (AVAudioPlayer*) tock;
+ (AVAudioPlayer*) withResourceName: (NSString*) aName;
@end

我发现这个systemSoundID列表对于直接访问声音ID非常有用。

例如,要播放一个按键,请按tock键

#define systemSoundID    1104
AudioServicesPlaySystemSound (systemSoundID);

您还需要在项目中添加AudioToolbox框架,并将
#include
添加到.m或.h文件中

所有系统声音列表:

导入AVKit后,您可以通过以下方式播放所有这些声音:

AudioServicesPlaySystemSound (systemSoundID);

您可以将其用于所有默认系统音频

例如,对于轻敲声音用户:

AudioServicesPlaySystemSound(1104);
对于积极的声音,请使用以下方法:

 AudioServicesPlaySystemSound(1054);
 AudioServicesPlaySystemSound(1053);
而且,消极的声音使用这个:

 AudioServicesPlaySystemSound(1054);
 AudioServicesPlaySystemSound(1053);

您可以看到完整的列表。

改编自@yannc2021

如果您想在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,您可以查看示例

编辑: 好的,下面是这个例子中最重要的代码:

    ///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)")
                }
            }
        }
该示例在表视图中显示系统声音文件。按此功能中所示播放声音:

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)")
        }
    }
其中
model.audioPlayer
只是
AVAudioPlayer
的一个实例:

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

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

实施@Krishnabhadra

Swift 4+

注意:仅在真实设备上试用:

或者您可以尝试使用URL作为-


这将播放大多数macOS系统声音

#包括
对于(int i=0;i<50;i++){
NSLog(@“播放%i”,i);
AudioServicesPlaySystemSound(一);
[NSThread sleepForTimeInterval:1.0];
}


在链接的示例项目中,它在ReadMe中明确指出没有可用的系统声音(在ios4中)。我认为使用uikit包中的命名文件不是一个好主意,因为它可以随时更改。链接线程中的想法是从模拟器捆绑包中提取声音,并将其包含在您自己的捆绑包中,如果仍然有点不稳定的话,效果会更好。非常好!只需检查零,这样你就不会崩溃。不要马上“处理”声音ID,你不会听到任何声音,(至少在我这样做的时候)你必须稍后处理它。。。如果在dealloc或viewDidUnload中合适,则可能出现此错误。第3行给出了此错误:“将Objective-C指针类型'id'转换为C指针类型CFURLRef'(也称为'const struct_CFURL*)需要桥接转换”。我在这里找到了解决方案:iosdeveloperzone.com/2012/07/28/…(这是一个弧形的东西。您必须将(CFURLRef)更改为(u_桥CFURLRef))。但“问题”是这样你只能听到3种声音。Tink.aiff、Tock.aiff和iPod Click.aiff。在设置->声音->文本音调(例如)中,有关于如何访问(其他)14个选项的想法吗?这个答案在ios 7中不适用。你可以看看这个:你显然忘记添加实际列表的链接了?如果我使用这个链接,我的应用程序会被禁止进入AppStore吗?这本书不在公共图书馆,所以可能很难复习。@Josip B。我从来没有遇到过复习上的问题code@DaniSpringer,我根据TUNER88的Objective C版本制作了一个swift版本。更新:@CQH不确定为什么我从未收到你回复的通知:/我已经使用了你的回购协议。看起来确实缺少了很多东西,或者至少我找不到许多文件名的声音ID。谢谢很高兴你喜欢回购协议。我希望它能帮助人们。我刚刚将其更新为Swift 3和iOS 10。@CQH您可以添加短信声音吗?比如“圆圈”?嗨,丹尼斯普林格。不幸的是,我无法处理alert sounds文件夹。任何帮助都将不胜感激。任何人都可以使用
AudioToolbox
而不是
AVKit
来支持早期的iOS版本。你在哪里找到这个?@Daniel我提到了GitHub链接。你也可以通过跳转到定义来检查。我的意思是,通过阅读官方文档,你在哪里找到了这个
CreateSystemSoundID
。Xcode还将模拟器iOS系统文件捆绑在其自身中。这不同于
~/Library/Developer/CoreSimulator
(仅限用户空间文件)系统文件位于此处:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Audio/UISounds
let url = URL(fileURLWithPath: "/System/Library/Audio/UISounds/payment_success.caf")
var soundID: SystemSoundID = 0
AudioServicesCreateSystemSoundID(url as CFURL, &soundID)
AudioServicesPlaySystemSound(soundID);