Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to generate sound with code below. Everthing is fine there is no error. But when I executed this code, there is no sound. How can I fix this problem ?

By the way, I'm using this example : http://www.tmroyal.com/playing-sounds-in-swift-audioengine.html

var ae:AVAudioEngine
var player:AVAudioPlayerNode?
var mixer:AVAudioMixerNode
var buffer:AVAudioPCMBuffer

ae = AVAudioEngine()
player = AVAudioPlayerNode()
mixer = ae.mainMixerNode;
buffer = AVAudioPCMBuffer(pcmFormat: player!.outputFormat(forBus:0), frameCapacity: 100)
buffer.frameLength = 100

// generate sine wave.
var sr:Float = Float(mixer.outputFormat(forBus:0).sampleRate)
var n_channels = mixer.outputFormat(forBus:0).channelCount

var i:Int=0
while i < Int(buffer.frameLength) {
    var val = sinf(441.0*Float(i)*2*Float(M_PI) / Float(sr))
    buffer.floatChannelData?.pointee[i] = val * 0.5
    i+=Int(n_channels)
}

// setup audio engine
ae.attach(player!)
ae.connect(player!, to: mixer, format: player!.outputFormat(forBus: 0))

ae.prepare()
try! ae.start()
// play player and buffer
player!.scheduleBuffer(buffer, at: nil, options: .loops, completionHandler: nil)
player!.play()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
974 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your AVAudioEngine looks like it's a local variable - that will go out of scope and be deallocated. Assign it to a class instance variable and maybe you'll hear some sound.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...