使用两个不同的滑块设置左右耳机音量
Posted
技术标签:
【中文标题】使用两个不同的滑块设置左右耳机音量【英文标题】:Set left and right headphone volume using two different sliders 【发布时间】:2020-12-09 19:11:24 【问题描述】:我正在生成不同频率的波声,用户应该只使用耳机听到这种波声,他/她将。为了实现波浪声音,我在下面编写了完美的代码。 但问题是:从过去 5 天开始,我尝试分别设置左右耳机的音量,但没有成功。
class Synth
// MARK: Properties
public static let shared = Synth()
public var volume: Float
set
audioEngine.mainMixerNode.outputVolume = newValue
get
audioEngine.mainMixerNode.outputVolume
public var frequencyRampValue: Float = 0
public var frequency: Float = 440
didSet
if oldValue != 0
frequencyRampValue = frequency - oldValue
else
frequencyRampValue = 0
private var audioEngine: AVAudioEngine
private lazy var sourceNode = AVAudiosourceNode _, _, frameCount, audioBufferList in
let ablPointer = UnsafeMutableAudioBufferListPointer(audioBufferList)
let localRampValue = self.frequencyRampValue
let localFrequency = self.frequency - localRampValue
let period = 1 / localFrequency
for frame in 0..<Int(frameCount)
let percentComplete = self.time / period
let sampleVal = self.signal(localFrequency + localRampValue * percentComplete, self.time)
self.time += self.deltaTime
self.time = fmod(self.time, period)
for buffer in ablPointer
let buf: UnsafeMutableBufferPointer<Float> = UnsafeMutableBufferPointer(buffer)
buf[frame] = sampleVal
self.frequencyRampValue = 0
return noErr
private var time: Float = 0
private let sampleRate: Double
private let deltaTime: Float
private var signal: Signal
// MARK: Init
init(signal: @escaping Signal = Oscillator.square)
audioEngine = AVAudioEngine()
let mainMixer = audioEngine.mainMixerNode
let outputNode = audioEngine.outputNode
let format = outputNode.inputFormat(forBus: 0)
sampleRate = format.sampleRate
deltaTime = 1 / Float(sampleRate)
self.signal = signal
let inputFormat = AVAudioFormat(commonFormat: format.commonFormat,
sampleRate: format.sampleRate,
channels: 1,
interleaved: format.isInterleaved)
audioEngine.attach(sourceNode)
audioEngine.connect(sourceNode, to: mainMixer, format: inputFormat)
audioEngine.connect(mainMixer, to: outputNode, format: nil)
mainMixer.outputVolume = 0
audioEngine.mainMixerNode.pan = 100 // this does not work,
//audioEngine.mainMixerNode.pan = 1.0 // this also does not work
do
try audioEngine.start()
catch
print("Could not start engine: \(error.localizedDescription)")
//This function will be called in view controller to generate sound
public func setWaveformTo(_ signal: @escaping Signal)
self.signal = signal
使用上面的代码,我可以在左右耳机中正常听到波声。 我尝试将 audioEngine.mainMixerNode.pan 用于值 100 和 -100 以及 -1.0 和 1.0 但这并没有做出任何改变。
【问题讨论】:
我看不到您在代码中的任何位置设置pan
。如果你能证明这一点会有所帮助。
我已经更新了代码,请检查。 (在连接语句之后)
【参考方案1】:
我尝试将 audioEngine.mainMixerNode.pan 用于值 100 和 -100,但这并没有做出任何改变。
pan
value 的允许范围是 -1.0, 1.0。您说您使用的值超出了该范围,因此它们没有效果也就不足为奇了。请改用 0.75 或 -0.75。
【讨论】:
您是否将其称为左侧的 audioEngine.mainMixerNode.pan = -1.0 和右侧的 audioEngine.mainMixerNode.pan = 1.0?请详细说明。以上是关于使用两个不同的滑块设置左右耳机音量的主要内容,如果未能解决你的问题,请参考以下文章