使用 AVAudioPlayer 在 iOS 中自动平移
Posted
技术标签:
【中文标题】使用 AVAudioPlayer 在 iOS 中自动平移【英文标题】:Autopan in iOS with AVAudioPlayer smoothly 【发布时间】:2019-11-20 09:02:40 【问题描述】:我正在尝试使用 AVaudioPlayer 构建自动平移(在左、中、右声道之间移动音频)来播放我的音乐文件。我可以通过 AVAudioPlayer.pan 方法得到它。通过在我的 swift 代码中使用计时器来实现自动平移。现在的问题是,音频播放不流畅,并且介于两者之间。
这是我现在的代码,
class AudioPlayer: UIViewController
var player = AVAudioPlayer()
override func viewDidLoad()
super.viewDidLoad()
prepareAudiosession()
func prepareAudioSession()
let audioFileName = "LPNumb"
let audioFileExtension = "mp3"
guard let filePath = Bundle.main.path(forResource: audioFileName, ofType: audioFileExtension) else
print("Audio file not found at specified path")
return
do
let alertSound = URL(fileURLWithPath: filePath)
try? player = AVAudioPlayer(contentsOf: alertSound)
catch
print(error)
@IBAction func play(_ sender: AnyObject)
player.play()
if player.isPlaying
_ = Timer.scheduledTimer(timeInterval: 0.50, target: self, selector: #selector(self.update1), userInfo: nil, repeats: true)
_ = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.update2), userInfo: nil, repeats: true)
_ = Timer.scheduledTimer(timeInterval: 1.50, target: self, selector: #selector(self.update3), userInfo: nil, repeats: true)
@objc func update1()
player.pan = 0
@objc func update2()
player.pan = 1
@objc func update3()
player.pan = -1
我想将输出音频设为 MONO,并要求音频能够顺利播放 AUTOPANNED。
【问题讨论】:
【参考方案1】:我认为,您只需为这项任务制作一个 Timer。查看代码:
import UIKit
import AVFoundation
enum PanState
case up
case down
class ViewController: UIViewController
var audioPlayer: AVAudioPlayer?
var timerForPan: Timer?
var pan: Double = 0.0
var panState: PanState = .up
override func viewDidLoad()
super.viewDidLoad()
if let path = Bundle.main.path(forResource: "LPNumb", ofType: "mp3")
let record = URL(fileURLWithPath: path)
setupRecordToPlayer(from: record)
setTimers()
func setTimers()
timerForPan = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updatePan), userInfo: nil, repeats: true)
func setupRecordToPlayer(from url: URL)
do
audioPlayer = try AVAudioPlayer(contentsOf: url)
catch let error
debugPrint(error.localizedDescription)
@IBAction func playButtonPressed(_ sender: UIButton)
audioPlayerToPlay()
@objc func updatePan()
if audioPlayer?.isPlaying ?? false
switch panState
case .up:
self.pan += 0.1
if pan >= 1
self.panState = .down
case .down:
self.pan -= 0.1
if pan <= -1
self.panState = .up
audioPlayer?.pan = Float(self.pan)
/// Prepare Audio player to play
func audioPlayerToPlay()
audioPlayer?.prepareToPlay()
do
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
catch
print(error.localizedDescription)
audioPlayer?.play()
【讨论】:
,非常感谢。这是执行平移任务的最佳可能性..以上是关于使用 AVAudioPlayer 在 iOS 中自动平移的主要内容,如果未能解决你的问题,请参考以下文章
Swift 3 iOS - 与 AVAudioPlayer 同步暂停
iOS 7:使用 AVAudioPlayer 的简单音频控件?
iOS使用虚拟AVAudioPlayer从铃声切换到系统音量
iOS - AVAudioPlayer 在后台不会继续播放下一首歌曲