首页 > 解决方案 > Swift 在读取原始数据文件并通过 audioPlayerNode.scheduleBuffer(audioFileBuffer) 播放时,我的音频质量很差

问题描述

我正在从原始文件中读取音频数据,然后将其转换为音频缓冲区。当我通过 audioPlayerNode 播放声音时,它会播放但音质不好。

func playMario() {
         //See if the file exists.
        guard let fileUrl: URL = Bundle.main.url(forResource: "mario", withExtension: "raw") else {
                print("return");
            return
        }

        do {
            // Get the raw data from the file.
            let rawData: Data = try Data(contentsOf: fileUrl)

            // Return the raw data as an array of bytes.
           // let bytes: [UInt8] = [UInt8](rawData)
            
             let newBytes = Array(rawData)
            
            // Convert byte array to audio buffer
            let buffer = bytesToAudioBuffer(newBytes)
            
           //starting of the player
            audioEngine.attach(audioPlayerNode)
           audioEngine.connect(audioPlayerNode, to:audioEngine.mainMixerNode, format: buffer.format)

            audioEngine.prepare()
            try? audioEngine.start()
            audioPlayerNode.play()
            audioPlayerNode.scheduleBuffer(buffer)
        } catch {
            print("Couldn't read the file.");
        }
    }
    
func bytesToAudioBuffer(_ buf: [UInt8]) -> AVAudioPCMBuffer {
        //original sample rate 44100.0 //pcmFormatFloat32
       let fmt = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 7000, channels: 1, interleaved: true)
    
        let frameLength = UInt32(buf.count) / (fmt?.streamDescription.pointee.mBytesPerFrame)!

        let audioBuffer = AVAudioPCMBuffer(pcmFormat: fmt!, frameCapacity: frameLength)
        audioBuffer!.frameLength = frameLength

        let dstLeft = audioBuffer?.floatChannelData![0]

        buf.withUnsafeBufferPointer {
            let src = UnsafeRawPointer($0.baseAddress!).bindMemory(to: Float.self, capacity: Int(frameLength))
            dstLeft!.initialize(from: src, count: Int(frameLength))
        }

        return audioBuffer!
    }

标签: iosswiftaudio-streaming

解决方案


推荐阅读