swift Swift Playground展示了如何使用AVAudioPlayerNode,AVAudioMixerNode,AVAudioEng在背景音频文件上播放多个wav文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift Swift Playground展示了如何使用AVAudioPlayerNode,AVAudioMixerNode,AVAudioEng在背景音频文件上播放多个wav文件相关的知识,希望对你有一定的参考价值。
import AVFoundation
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
class AudioPlayer {
var backgroundAudioFile:AVAudioFile
var topAudioFiles: [AVAudioFile] = []
var engine:AVAudioEngine
var backgroundAudioNode: AVAudioPlayerNode
var topAudioAudioNodes = [AVAudioPlayerNode]()
var mixer: AVAudioMixerNode
var timer: Timer!
var urls: [URL] = []
init (_ url: URL, urls: [URL] = []) {
backgroundAudioFile = try! AVAudioFile(forReading: url)
topAudioFiles = urls.map { try! AVAudioFile(forReading: $0) }
engine = AVAudioEngine()
mixer = AVAudioMixerNode()
engine.attach(mixer)
engine.connect(mixer, to: engine.outputNode, format: nil)
self.urls = urls
backgroundAudioNode = AVAudioPlayerNode()
for _ in topAudioFiles {
topAudioAudioNodes += [AVAudioPlayerNode()]
}
}
func start() {
engine.attach(backgroundAudioNode)
engine.connect(backgroundAudioNode, to: mixer, format: nil)
backgroundAudioNode.scheduleFile(backgroundAudioFile, at: nil, completionHandler: nil)
try! engine.start()
backgroundAudioNode.play()
for node in topAudioAudioNodes {
engine.attach(node)
engine.connect(node, to: mixer, format: nil)
}
try! engine.start()
// simulate rescheduling files played on top of background audio
DispatchQueue.global().async { [unowned self] in
for i in 0..<1000 {
sleep(2)
let index = i % self.topAudioAudioNodes.count
let node = self.topAudioAudioNodes[index]
node.scheduleFile(self.topAudioFiles[index], at: nil, completionHandler: nil)
node.play()
}
}
}
}
let bundle = Bundle.main
let beepLow = bundle.url(forResource: "beeplow", withExtension: "wav")!
let beepMid = bundle.url(forResource: "beepmid", withExtension: "wav")!
let backgroundAudio = bundle.url(forResource: "backgroundAudio", withExtension: "wav")!
let audioPlayer = AudioPlayer(backgroundAudio, urls: [beepLow, beepMid])
audioPlayer.start()
以上是关于swift Swift Playground展示了如何使用AVAudioPlayerNode,AVAudioMixerNode,AVAudioEng在背景音频文件上播放多个wav文件的主要内容,如果未能解决你的问题,请参考以下文章
如何检查 Playground 的 swift 版本?
初尝Swift-用Playground来学习Swift语言
Swift 中的 Playground 不会使用 Firebase
在 Playground 的“SupportCode.swift”中导入第 3 方框架
在 Playground 中的 swift 3 中添加延迟似乎不准确
如何使用 Swift 3 Playground 读取 Resources 目录中的文本文件?