如何在swift中编写pow()并修复错误?

时间:2015-07-04 17:22:41

标签: swift

我试图在swift中编写一个pow函数,这是我的代码:

var recorder: AVAudioRecorder!
var levelTimer = NSTimer()
var lowPassResults: Double = 0.0

override func viewDidLoad() {
    super.viewDidLoad()
    let url = NSURL.fileURLWithPath("dev/null")
    //numbers are automatically wrapped into NSNumber objects, so I simplified that to [NSString : NSNumber]
    var settings : [NSString : NSNumber ] = [AVSampleRateKey: 44100.0, AVFormatIDKey: kAudioFormatAppleLossless, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.Max.rawValue]
    var error: NSError?
    self.recorder = [[AVAudioRecorder alloc] initWithURL:soundFileURL, settings:recordSettings, error:&error];
    if((recorder) != nil){
        recorder.prepareToRecord()
        recorder.meteringEnabled = true
        recorder.record()
        levelTimer = NSTimer.scheduledTimerWithTimeInterval(0.03, target: self, selector: Selector("listenForBlow"), userInfo: nil, repeats: true)
    }
    else{
        NSLog("%@", "Fehler an dieser Stelle");
    }
}
func levelTimerCallback(timer:NSTimer) {
    recorder.updateMeters()
    let ALPHA: Double = 0.05
    var peakPowerForChannel: Double = pow(10, (0.05 * [self.recorder.peakPowerForChannel(0)]))
    lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * lowPassResults;

    NSLog("@Average input: %f Peak input: %f Low pass results: %f", [recorder.averagePowerForChannel(0)], [recorder.peakPowerForChannel(0)], lowPassResults);
}

我在两行中遇到错误而且我不知道如何修复它们。 这是此行中的第一个错误:(错误:"预期','分隔符)。是否存在我忽略的语法错误?

self.recorder = [[AVAudioRecorder alloc] initWithURL:soundFileURL, settings:recordSettings, error:&error];

这是另一个错误:"无法找到' *'接受提供的参数"。我知道类型必须相同(Double * Double)。但确切的错误在哪里?

var peakPowerForChannel: Double = pow(10, (0.05 * [self.recorder.peakPowerForChannel(0)]))

P.S。:我知道有很多这样的问题,但我找不到快速的答案。提前谢谢!!

1 个答案:

答案 0 :(得分:3)

使用Swift而不是Objective-C语法来初始化录音机:

recorder = try AVAudioRecorder(URL:…settings:…)

要计算peakPowerForChannel,请知道10将是IntpeakPowerForChannel(_:)会返回Float,而不是Double。您需要明确地投射这些:

var peakPowerForChannel : Double = pow(Double(10), (0.05 * Double(recorder.peakPowerForChannel(0))))

此外,由于pow(_: _:)返回Double,您可以删除peakPowerForChannel的类型规范:

var peakPowerForChannel = pow(Double(10), (0.05 * Double(recorder.peakPowerForChannel(0))))