如何在 Swift 3 中使用 AVAudioPlayer 播放 .ogg 音频文件?

Posted

技术标签:

【中文标题】如何在 Swift 3 中使用 AVAudioPlayer 播放 .ogg 音频文件?【英文标题】:how to play .ogg audio file using AVAudioPlayer in Swift 3? 【发布时间】:2018-01-25 05:45:11 【问题描述】:

我正在尝试使用此代码使用 AVAudioPlayer 播放音频文件:

    let urlString = "http://192.168.1.19:8080/download/2"
    let url = URL(string: urlString)!
    print("the url = \(url)")

    do 
        let data = try Data.init(contentsOf: url)
        self.audioPlayer = try AVAudioPlayer.init(data: data)
        self.audioPlayer.prepareToPlay()

        self.audioPlayer.play()
     catch 
        print("couldn't load file")
    

音频格式为 Ogg Vorbis (.ogg),总是无法加载。播放此 .ogg 文件的任何解决方案?

【问题讨论】:

Playing an ogg stream in ios的可能重复 该答案已弃用,链接无法打开,并且已经 5 年了,甚至在 Swift 发布日期之前 所有链接都对我有用,尽管您可能不想使用“Precompiled Ogg Vorbis Libraries for iOS”链接后面的预编译框架,因为这些都是旧的。然而,GitHub 项目的最终链接包含更新版本。注意支持bridge Objective-C code into Swift 我无法重现 .ogg 文件(可能不支持),所以我不得不将其转换为 mp3(ffmpeg 处理媒体文件的好工具)。 我也想玩.ogg 【参考方案1】:

使用 https://github.com/Alterplay/APAudioPlayer 这个播放器非常适合播放 .ogg 文件以及所有类型的文件

【讨论】:

以上是关于如何在 Swift 3 中使用 AVAudioPlayer 播放 .ogg 音频文件?的主要内容,如果未能解决你的问题,请参考以下文章

(iphone) 如何使用 AVAudioPlayer 顺序播放声音?

如何在 Swift 3 中使用 BFTask?

如何在 Swift 3 中使用 NSLocale 获取国家代码

如何在 Swift 3 中使用 UnsafeMutablePointer?

如何在 Swift 3.0 中使用 keysSortedByValue?

如何使用 Swift 3 在 UIView 中覆盖 requiresConstraintBasedLayout?