我正在尝试在 swift AVFoundations 中混合两个音频文件。我有一个混合两个音频并同时播放它们的解决方案。我真正想要的是在一段时间后开始第二个音频。例如音频 1 播放然后第二个音频在 10(给定时间)秒后开始播放。任何帮助表示赞赏。提前致谢。
private var audioFiles: Array<String>
private var audioEngine: AVAudioEngine = AVAudioEngine()
private var mixer: AVAudioMixerNode = AVAudioMixerNode()
func Play() {
// do work in a background thread
DispatchQueue.global(qos: .background).async {
self.audioEngine.attach(self.mixer)
self.audioEngine.connect(self.mixer, to: self.audioEngine.outputNode, format: nil)
// !important - start the engine *before* setting up the player nodes
try! self.audioEngine.start()
let fileManager = FileManager.default
for audioFile in self.audioFiles {
// Create and attach the audioPlayer node for this file
let audioPlayer = AVAudioPlayerNode()
self.audioEngine.attach(audioPlayer)
// Notice the output is the mixer in this case
self.audioEngine.connect(audioPlayer, to: self.mixer, format: nil)
let fileUrl = NSURL.init(fileURLWithPath: fileName.removingPercentEncoding!)
var file : AVAudioFile
// We should probably check if the file exists here ¯\_(ツ)_/¯
try! AVAudioFile.init(forReading: fileUrl.absoluteURL!)
audioPlayer.scheduleFile(file, at: nil, completionHandler: nil)
audioPlayer.play(at: nil)
}
}
}
最佳答案
你应该使用 scheduleSegment .
func scheduleWithOffset(_ offset: TimeInterval) {
let samplerate1 = file1.processingFormat.sampleRate
player1.scheduleSegment(file1,
startingFrame: 0,
frameCount: AVAudioFrameCount(file1.length),
at: AVAudioTime(sampleTime: 0, atRate: samplerate1))
let samplerate2 = file2.processingFormat.sampleRate
player2.scheduleSegment(file2,
startingFrame: 0,
frameCount: AVAudioFrameCount(file2.length),
at: AVAudioTime(sampleTime: AVAudioFramePosition(offset * samplerate2), atRate: samplerate2))
//This can take an indeterminate amount of time, so both files should be prepared before either starts.
player1.prepare(withFrameCount: 8192)
player2.prepare(withFrameCount: 8192)
// Start the files at common time slightly in the future to ensure a synchronous start.
let hostTimeNow = mach_absolute_time()
let hostTimeFuture = hostTimeNow + AVAudioTime.hostTime(forSeconds: 0.2);
let startTime = AVAudioTime(hostTime: hostTimeFuture)
player1.play(at: startTime)
player2.play(at: startTime)
}
关于ios - 使用不同的起点条目快速混合两个音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53341213/