ios - 类型“字符串”没有成员“播放”
问题描述
尝试在 xcode 10.1 中构建木琴时,在 iOS12 上使用 swift 4.2,我使用按钮播放 .wav 文件并输入以下代码,但出现以下错误:
“类型‘字符串’没有成员‘播放’”
func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
try AVAudioSession.sharedInstance().setActive(true)
/* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
解决方案
如果您在 Xcode 上单击跳转到定义,AVAudioSession
将打开该类的原始源文件,您可以从那里查看该类中每个方法的结构。这有助于查看每个函数的结构和确定每个函数的数据参数。此外,在与不同 iOS 部署目标兼容的类函数的每个变体上方都有注释,由@available(iOS 11.0, *)
注释指示。我们专注open func setCategory
于这个类中的函数。
原始源文件中的有用信息
Allowed categories: AVAudioSessionCategoryPlayback
Allowed modes: AVAudioSessionModeDefault, AVAudioSessionModeMoviePlayback, AVAudioSessionModeSpokenAudio
Allowed options: None. Options are allowed when changing the routing policy back to Default
我在函数中编辑了类别和模式参数,如下所示:
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, mode: AVAudioSessionModeDefault, options: [.mixWithOthers, .allowAirPlay])
print("Playback OK")
try AVAudioSession.sharedInstance().setActive(true)
print("Session is Active")
} catch {
print(error)
}
推荐阅读
- openssl - 使用主题中的“T”和“uidNumber”属性创建 CSR 时出错
- google-app-engine - Google App Engine - 什么算作前端?
- c++ - 根据分量 1、2(和 3)对空间(2D/3D)向量的向量进行排序
- docker - Docker 工具箱 TLSParameterError
- docker - Docker - 我们可以通过使用 Docker 社区版在容器内运行的应用程序来管理身份验证系统、用户会话和 cookie 吗?
- javascript - Uncaught SyntaxError: Unexpected token ,
- string - 如何将整数转换为没有 0x 的十六进制字符串(Julia 1.0)
- python-2.7 - 无法在另一台计算机上运行可执行文件
- python - 用 python 抓取网页。无法访问 td 元素
- bash - bash 函数使用 stdin 两次