首页 > 解决方案 > 类型“字符串”没有成员“播放”

问题描述

尝试在 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)
        }
    }

标签: iosswiftswift4.2

解决方案


如果您在 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)
}

推荐阅读