在iOS应用中使用现有的系统声音 [Swift|]

67

我能否在我的应用程序中使用现有的苹果系统声音? 我想用Swift编写一个简单的应用程序,完成以下步骤:

  1. 读取 / 获取设备上所有可用系统声音的列表(我认为它们位于 /System/Library/Audio/UISounds/
  2. 在屏幕上显示列表
  3. 如果我点击了列表项,则播放这些声音

所以它基本上与您在 iPhone 上选择新铃声时相同。

我认为某些应用程序正在使用这些声音,或者他们是复制/购买的吗?


1
值得注意的是,/System/Library/Audio/UISounds/ 存在于物理设备上,但在模拟器中不存在。 - Derek Soike
4个回答

183

你可以使用这段 Swift 5 代码播放系统声音:

// import this
import AVFoundation

// create a sound ID, in this case its the tweet sound.
let systemSoundID: SystemSoundID = 1016

// to play sound
AudioServicesPlaySystemSound(systemSoundID)

我能找到的最新声音列表在这里

文档参考

以下是它们的所有声音示例: https://www.youtube.com/watch?v=TjmkmIsUEbA


3
苹果公司在哪里有记录这个? - Meriw
7
开发者使用iOS系统声音是否有苹果公司的指南? - Dave G
2
如果您导入AVFoundation,则可以在一行中完成其余操作:AudioServicesPlaySystemSound(SystemSoundID(1016)) - peacetype
3
根据AudioServicesPlaySystemSound的文档:“在使用此函数之前,请调用AudioServicesCreateSystemSoundID(::)函数获取系统声音。”同时,在AudioServicesPlayAlertSound中也提到:“iOS应用程序无法使用系统提供的警报声和系统提供的用户界面声效。” - biomiker
1
@kenjikato 这是一个非常流行的问题。如果您知道更好的播放这些声音的方法,请花时间提交答案。 - Beau Nouvelle
显示剩余3条评论

25

Swift 4

import AVFoundation

AudioServicesPlayAlertSound(SystemSoundID(1322))

13
谢谢。这是所有声音ID的链接:http://iphonedevwiki.net/index.php/AudioServices。 - Mayuri R Talaviya

10

这是一种快速测试声音的方法。

import AVFoundation

func displaySoundsAlert() {
    let alert = UIAlertController(title: "Play Sound", message: nil, preferredStyle: UIAlertController.Style.alert)
    for i in 1000...1010 {
        alert.addAction(UIAlertAction(title: "\(i)", style: .default, handler: {_ in
            AudioServicesPlayAlertSound(UInt32(i))
            self.displaySoundsAlert()
        }))
    }
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
    self.present(alert, animated: true, completion: nil)
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接