我正在使用 AVFoundation
框架。每当玩家播放缓冲区时,我的背景音乐就会停止,所以我使用下面的代码让它继续播放,而不管 AVFoundation
播放器。
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: [.mixWithOthers,.allowBluetooth])
try audioSession.setMode(AVAudioSessionModeDefault)
try audioSession.setActive(true)
它确实有效,但问题是背景音乐的质量受到严重影响。只要AVPlayer
播放缓冲区,音乐就不再具有低音效果。
我希望在使用AVPlayer
时不会中断背景音乐。有可能吗?
更新:如果有人想检查,我添加了完整的代码。一旦打开应用程序或使用此代码激活会话,就可以感受到背景itune音乐的不同。
class ViewCosdfntroller: UIViewController {
var engine = AVAudioEngine()
let audioSession = AVAudioSession.sharedInstance()
let player = AVAudioPlayerNode()
let mixer = AVAudioMixerNode()
override func viewDidLoad() {
super.viewDidLoad()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: [.mixWithOthers,.allowBluetooth])
try audioSession.setMode(AVAudioSessionModeDefault)
try audioSession.setActive(true)
} catch {
}
let input = engine.inputNode
let bus = 0
let inputFormat = input.outputFormat(forBus: bus)
let recordingFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 11025.0, channels: 1, interleaved: false)
engine.attach(player)
engine.attach(mixer)
engine.connect(input, to: mixer, format: input.outputFormat(forBus: 0))
engine.connect(player, to: engine.mainMixerNode, format: recordingFormat)
mixer.installTap(onBus: bus, bufferSize: AVAudioFrameCount(inputFormat.sampleRate * 0.4), format: inputFormat, block: { (buffer: AVAudioPCMBuffer!, time: AVAudioTime!) -> Void in
let Converter:AVAudioConverter = AVAudioConverter.init(from: inputFormat, to: recordingFormat!)!
let newbuffer = AVAudioPCMBuffer(pcmFormat: recordingFormat!,frameCapacity: AVAudioFrameCount((recordingFormat?.sampleRate)! * 0.4))
let inputBlock : AVAudioConverterInputBlock = { (inNumPackets, outStatus) -> AVAudioBuffer? in
outStatus.pointee = AVAudioConverterInputStatus.haveData
let audioBuffer : AVAudioBuffer = buffer
return audioBuffer
}
var error : NSError?
Converter.convert(to: newbuffer!, error: &error, withInputFrom: inputBlock)
self.player.scheduleBuffer(newbuffer!)
})
do {
try! engine.start()
player.play()
} catch {
print(error)
}
}
}
答案 0 :(得分:0)
我认为你需要这个:
try audioSession.setCategory(AVAudioSessionCategoryAmbient)
文档: https://developer.apple.com/documentation/avfoundation/avaudiosessioncategoryambient
当您使用此类别时,来自其他应用的音频会与您的音频混合
答案 1 :(得分:0)
除非这是一些奇怪的混合怪癖,否则您报告的质量变化可能只是记录类别将默认音频输出设备更改为微小的,小巧的接收器(因为电话,不要问)。通过在.defaultToSpeaker
电话中添加setCategory()
来覆盖此行为:
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: [.mixWithOthers,.allowBluetooth, .defaultToSpeaker])