将magicCookie从音频文件复制到音频队列失败

问题描述 投票:0回答:1

我可能是在Adamson / Avila着名的《学习核心音频》一书的帮助下尝试学习CoreAudio的第1000个人。大概第1000个人正在努力将原始代码示例转换为现代Swift。

[我从书的第5章得到了示例(使用AudioQueueService播放文件),但是只要我尝试播放使用magicCookie格式的文件,代码就会崩溃。

我将代码简化为仅产生错误所需的代码:

import AudioToolbox

// user data struct needed for the callback

struct MyPlayer {
    var playbackFile: AudioFileID?
}

// callback stub

func myAQOutputCallback(inUserData: UnsafeMutableRawPointer?, inQueue: AudioQueueRef, inCompleteAQBuffer: AudioQueueBufferRef) {

}

func copyEncoderCookieToQueue(_ file: AudioFileID, _ queue: AudioQueueRef) {

    var propertySize: UInt32 = 0
    let result: OSStatus = AudioFileGetPropertyInfo(file, kAudioFilePropertyMagicCookieData, &propertySize, nil)

    if result == noErr && propertySize > 0 {

        var magicCookie = UnsafeMutableRawPointer.allocate(byteCount:Int(propertySize), alignment: Int(propertySize))

        var error = AudioFileGetProperty(file, kAudioFilePropertyMagicCookieData, &propertySize, &magicCookie)

        // up to this point everything works as expected

        error = AudioQueueSetProperty(queue, kAudioQueueProperty_MagicCookie, magicCookie, propertySize)
        magicCookie.deallocate()
    }
}

func main() {

    let kPlaybacklFileLocation = "/Users/\(NSUserName())/Desktop/70s Ballad Drums 01.caf"
    var player = MyPlayer()

    let myFileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, kPlaybacklFileLocation as CFString, .cfurlposixPathStyle, false)
    var error = AudioFileOpenURL(myFileURL!, .readPermission, 0, &player.playbackFile)

    var dataFormat = AudioStreamBasicDescription()
    var propSize = UInt32(MemoryLayout.size(ofValue: dataFormat))
    error = AudioFileGetProperty(player.playbackFile!, kAudioFilePropertyDataFormat, &propSize, &dataFormat)

    var queue: AudioQueueRef?
    error = AudioQueueNewOutput(&dataFormat, myAQOutputCallback, &player, nil, nil, 0, &queue)

    copyEncoderCookieToQueue(player.playbackFile!, queue!)
}

main()

要进行测试,您可以将GarageBand随附的Apples AppleLoop文件之一放到桌面上。 MagicCookie似乎可以正确提取,但是尝试将其写入AudioQueue会导致错误EXC_BAD_ACCESS,据我了解,这表示某事正在尝试访问已释放的对象,但据我所知,所有参数仍应有效。

我不知道如何进一步调查导致问题的原因。

swift core-audio
1个回答
0
投票

尝试彻底关闭Audio Queue后,直到多(200?)毫秒才取消分配魔术曲奇存储。队列可以调用使用知道何时Cookie的异步线程。

© www.soinside.com 2019 - 2024. All rights reserved.