gpt4 book ai didi

ios - 音频无法播放 Xcode 10.1 Swift 4

转载 作者:行者123 更新时间:2023-11-29 05:17:36 25 4
gpt4 key购买 nike

我终于开始学习播放声音,但我没有成功在我的应用程序中播放声音。我仍然使用 Xcode 10.1/Swift4(不是 4.2),因为我还无法升级到 Mojave/Catalina。我读了很多关于.setCategory(.playback, mode: .default)的帖子Xcode 10.1 中存在错误,但找到的解决方案适用于 Swift 4.2。另外category:mode:预计类型为 String ,但在文档中该功能解释为:

func setCategory(_ category: AVAudioSession.Category, mode: AVAudioSession.Mode, options: AVAudioSession.CategoryOptions = []) throws

而且它们不是 String 类型。我在这里有点迷失了。

我的代码不会引发任何编译错误,但在控制台上运行时我得到:

AVAudioSessionUtilities.mm:106:getUInt32: -- Category Value Converter failed to find a match for string "ambient"

我在这里缺少什么?您能给我指出正确的方向来理解这个类别问题吗?一如既往,非常感谢您的时间和帮助。

这是应该播放声音的函数:

static func playOnceSound(soundToPlay: String) {
var player: AVAudioPlayer?
guard let url = Bundle.main.url(forResource: soundToPlay, withExtension: "mp3") else { return }



do {
// try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default) // Error: Type 'String' has no member 'playback'

try AVAudioSession.sharedInstance().setCategory("ambient", mode: "default", options: .defaultToSpeaker)
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.numberOfLoops = 1
player.volume = 1.0
player.play()

} catch let error {
print(error.localizedDescription)
}
}

最佳答案

您是否尝试过以这种方式输入环境和默认值,而不是使用字符串?另外,在 setCategory 之前实例化 Audio Session 对象:

var audioSession: AVAudioSession?

func setup() {
audioSession = AVAudioSession.sharedInstance()

do {
try audioSession.setCategory(AVAudioSession.Category.ambient, mode: .default, options: .defaultToSpeaker)
try audioSession.setActive(true)
}
catch {
print("Failed to set category", error.localizedDescription)
}
}

关于ios - 音频无法播放 Xcode 10.1 Swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59016781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com