繁体   English   中英

Swift 3.0 AVAudioPlayer 通过音乐播放音频

[英]Swift 3.0 AVAudioPlayer Playing audio over music

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

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、音乐)。 我该怎么做呢?

将应用程序的音频会话设置为在当前播放的音频上播放:

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

根据AVAudioSession标头, AVAudioSessionCategoryAmbient将播放带有音乐等的音频。

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

斯威夫特 5.3 更新

guard let url = Bundle.main.url(forResource: "INSERT_FILENAME", withExtension: "wav") else { return }

do {
    try AVAudioSession.sharedInstance().setCategory(.ambient, mode: .default)
    try AVAudioSession.sharedInstance().setActive(true)

    audioPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue)
    audioPlayer.volume = 1

    audioPlayer.play()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM