类型“字符串”没有成员“播放”

时间:2019-06-13 22:02:39

标签: ios swift swift4.2

当尝试在iOS12上使用swift 4.2在xcode 10.1中构建木琴时,我使用按钮播放.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)
        }
    }

3 个答案:

答案 0 :(得分:0)

我正在环顾StackOverflow,并借用了这段有效的代码,但我不知道这是否是常规的实现方式。

Swift 4.2

import AVFoundation
var player = AVAudioPlayer()

let url = URL(fileURLWithPath: Bundle.main.path(forResource: "note1", ofType: "wav")!)
    do {
        player = try AVAudioPlayer(contentsOf: url)
        player.play()
    } catch {
        print("couldn't load file :(")
    }

答案 1 :(得分:0)

func playSound() {

    let soundURL = Bundle.main.url(forResource: selectedSoundFileName, withExtension: "wav")
    do{
        audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
        audioPlayer.play()
    } catch {

    }
}

这是您可以尝试的另一种变体!让我知道这种格式是否适合您。很久以前,我自己在Udemy课程中构建了一个木琴应用程序。将声音文件直接放入项目并在其中运行比从我认为的任何地方拉取声音要容易得多。

这是我可以为您实现这一最“快捷”的方式。

答案 2 :(得分:0)

如果单击AVAudioSession上的跳转到定义,Xcode将打开该类的原始源文件,然后您可以在其中查看该类中每个方法的结构。这有助于查看每个功能的结构以及确定每个功能的数据参数。此外,在@available(iOS 11.0, *)注释所指示的类函数的每个变体上方,都有与不同的iOS部署目标兼容的注释。我们在此类中专注于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)
}