【问题标题】:Noise and distortion in Swift implementation of SDL audio callbackSDL 音频回调的 Swift 实现中的噪声和失真
【发布时间】:2020-07-18 19:45:33
【问题描述】:

我目前正在为 Mac OS 使用 Swift 构建游戏音乐播放器,使用 GME 生成声音缓冲区并使用 SDL 进行音频播放。我以前(并且成功地)使用SDL_QueueAudio 进行播放,但我需要对缓冲区处理进行更精细的控制,以确定歌曲进度、歌曲结束等。所以,这让我在SDL_AudioSpec API 中使用了 SDL_AudioCallback。

我可以听到歌曲播放,但伴随着噪音和失真(有时会根据我的尝试而回声)。

设置

var desiredSpec = SDL_AudioSpec()
desiredSpec.freq = Int32(44100)
desiredSpec.format = SDL_AudioFormat(AUDIO_U8)
desiredSpec.samples = 512
desiredSpec.channels = 2
desiredSpec.callback = { callback(userData: $0, stream: $1, length: $2) }

SDL_OpenAudio(&desiredSpec, nil)

回调

func callback(userData: UnsafeMutableRawPointer?, stream: UnsafeMutablePointer<UInt8>?, length: Int32) {
    // Half sample length to compensate for double byte Int16.
    var output = Array<Int16>.init(repeating: 0, count: Int(length / 2))

    // Generates stereo signed Int16 audio samples.
    gme_play(emulator, Int32(output.count), &output)

    // Converts Int16 samples to UInt8 samples expected by the mixer below. Then adds to buffer.
    var buffer = [UInt8]()
    for i in 0 ..< (output.count) {
        let uIntVal = UInt16(bitPattern: output[i])
        buffer.append(UInt8(uIntVal & 0xff))
        buffer.append(UInt8((uIntVal >> 8) & 0xff))
    }

    SDL_MixAudio(stream, buffer, Uint32(length), SDL_MIX_MAXVOLUME)
}

【问题讨论】:

    标签: swift macos sdl audiobuffer


    【解决方案1】:

    已解决! 最后,这足以让它发挥作用:

    desiredSpec.format = SDL_AudioFormat(AUDIO_S16)
    
    var buffer = Array<Int16>(repeating: 0, count: Int(length / 2))
    gme_play(emulator, Int32(output.count), &output)
    SDL_memcpy(stream, buffer, Int(length))
    

    【讨论】:

      猜你喜欢
      • 2016-08-25
      • 1970-01-01
      • 2013-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 2021-05-30
      相关资源
      最近更新 更多