问题
Can someone point me to a working version of Matt Gallagher's Tone Generator?
http://www.cocoawithlove.com/assets/objc-era/ToneGenerator.zip
As Matt says, it hasn't been updated and apparently got broken by newer APIs. I updated what I could figure out needed updating and now it compiles and runs with only deprecation warnings but all it does is make clicking sounds when the "Play" and "Stop" button are touched. I've gone through the code and looked at the documentation in Xcode for the API but it's a steep learning curve. I would love to have a working version so I could tinker with it to learn more. Has anyone updated it? Or a similar tone generator?
I tried using the ToneOutputUnit class from hotpaw2 by calling it as follows.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let unit = ToneOutputUnit()
unit.toneCount = 64000
unit.setFrequency(1000.0)
unit.setToneVolume(0.5)
unit.startToneForDuration(2.0)
unit.enableSpeaker()
print("ok")
}
}
I could see that the ToneOutputUnit code was being called and was stepping through the various functions but no sound was produced. I also tried calling 'enableSpeaker' before 'startToneForDuration' but also no sound. What am I missing?
回答1:
Of course Gene De Lisa is right. The "unit" variable needs to be declared outside of viewDidLoad so it doesn't get deallocated right away. Also, "unit.enableSpeaker()" needs to be before "unit.startToneForDuration(0.5)". However even with those 2 changes I got no sound. After more head scratching I found two scaling errors in hotpaw2's ToneOutputUnit.swift (in github).
1) In the function startToneForDuration the line "toneCount = Int32(round( time / sampleRate ))" should be "toneCount = Int32(time * sampleRate)".
2) And in the function setToneVolume the line "v0 = vol / 32768.0" should be "v0 = vol * 32768.0".
With those two changes it works and produces a tone with volume and duration that seem reasonable.
@Hotpaw2: I hope you will update your version in github. It's a nicely written class that will help others.
来源:https://stackoverflow.com/questions/38909493/matt-gallaghers-ios-tone-generator