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、音乐)将此音频发送到 运行。我该怎么做?
将应用程序的音频 session 设置为在当前播放的音频之上播放:
try? AVAudioSession.sharedInstance().setActive(true)
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
根据AVAudioSession
headers,AVAudioSessionCategoryAmbient
会播放带音乐的音频等
/* Use this category for background sounds such as rain, car engine noise, etc.
Mixes with other music. */
public let AVAudioSessionCategoryAmbient: String
Swift 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)
}
目前这是我在按下按钮时用来播放声音的代码。
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、音乐)将此音频发送到 运行。我该怎么做?
将应用程序的音频 session 设置为在当前播放的音频之上播放:
try? AVAudioSession.sharedInstance().setActive(true)
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
根据AVAudioSession
headers,AVAudioSessionCategoryAmbient
会播放带音乐的音频等
/* Use this category for background sounds such as rain, car engine noise, etc.
Mixes with other music. */
public let AVAudioSessionCategoryAmbient: String
Swift 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)
}