ios - Swift 3.0 AVAudioPlayer 通过音乐播放音频

标签 ios swift swift3 avaudioplayer

目前这是我用来在按下按钮时播放声音的代码。

var player: AVAudioPlayer?

    let url = Bundle.main.url(forResource: "Sound/yatch", withExtension: "mp3")!

    do {
        player = try AVAudioPlayer(contentsOf: url)
        guard let player = player else { return }

        player.prepareToPlay()
        player.play()
    } catch let error {
        print(error.localizedDescription)
    }

我正在尝试让此音频播放当前正在播放的内容(例如 Spotify、pandora、Music)。我该怎么做呢?

最佳答案

将您的应用程序的 Audio Session 设置为在当前播放的音频上播放:

try? AVAudioSession.sharedInstance().setActive(true)
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)

根据 AVAudioSession header ,AVAudioSessionCategoryAmbient 将播放带有音乐等的音频

/*  Use this category for background sounds such as rain, car engine noise, etc.
 Mixes with other music. */
public let AVAudioSessionCategoryAmbient: String

关于ios - Swift 3.0 AVAudioPlayer 通过音乐播放音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41312216/

相关文章:

ios - 获取 CGFloat 最接近的值

swift - API 调用似乎正在遍历并收集数据,但数据未显示在我的自定义表格 View 单元格中

ios - swift 3 : UITableViewCell disable selection style also disables selection

iOS SDK 4.0 & 4.1 添加图像到模拟器

ios - 字典(键,值)顺序

iphone - Interface Builder 文件中的未知类 CPTGraphHostingView

swift - 继续使用 NSbutton Swift 的下一个索引

ios - 如何阻止 GCD 调度 _after block 返回结果。可能很愚蠢

ios - 两个 pickerview 改变一个 imageview

ios - Google IOS 分析 V3 未在仪表板上注册