「[Swift]AVAudioEngineを使って曲の再生をする」の続きです。今回は、AVAudioEngineを使って曲にリバーブをかけます。主な流れは、リバーブのNodeを作って、それをAudioEngineへ追加して、Node同士を接続して、という感じです。
かけるリバーブは、loadFactoryPresetで、プリセットの中から選ぶことができます。
また、リバーブの強さ?深さ?は、wetDryMixで、0から100の間で設定できます。
「[Swift]AVAudioEngineを使って曲の再生をする」で作ったものに追記をして進めていますので、ご注意ください。
(続き:[Swift]AVAudioEngineを使ってDelayをかける)
できること
ソフトのバージョン
OS: OSX Yosemite 10.10.1
Xcode: 6.1
つくりかた
動画でご確認ください。
コード
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var buttonPlay: UIButton!
@IBOutlet weak var sliderReverb: UISlider!
var audioEngine: AVAudioEngine!
var audioFilePlayer: AVAudioPlayerNode!
var audioReverb: AVAudioUnitReverb!
var audioFile: AVAudioFile!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// AudioEngineの生成
audioEngine = AVAudioEngine()
// AVPlayerNodeの生成
audioFilePlayer = AVAudioPlayerNode()
// AVAudioFileの生成
audioFile = AVAudioFile(forReading: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("test", ofType: "mp3")!), error: nil)
// ReverbNodeの生成
audioReverb = AVAudioUnitReverb()
audioReverb.loadFactoryPreset(.LargeHall2)
audioReverb.wetDryMix = 0
// AVPlayerNodeとReverbNodeをAVAudioEngineへ追加
audioEngine.attachNode(audioFilePlayer)
audioEngine.attachNode(audioReverb)
// AVPlayerNodeとReverbNodeをAVAudioEngineへ接続
audioEngine.connect(audioFilePlayer, to: audioReverb, format: audioFile.processingFormat)
audioEngine.connect(audioReverb, to: audioEngine.mainMixerNode, format: audioFile.processingFormat)
// AVAudioEngineの開始
audioEngine.startAndReturnError(nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonPlayPressed(sender: UIButton) {
if (audioFilePlayer.playing) {
audioFilePlayer.pause()
buttonPlay.setTitle("PLAY", forState: .Normal)
} else {
audioFilePlayer.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
audioFilePlayer.play()
buttonPlay.setTitle("PAUSE", forState: .Normal)
}
}
@IBAction func sliderReverbChanged(sender: UISlider) {
audioReverb.wetDryMix = sliderReverb.value
}
}