swift - 读取 WAV 文件并将其转换为 Swift 中的振幅数组

标签 swift audio waveform

我在 udacity 上遵循了一个非常好的教程与一起探索音频应用的基础 swift .我想扩展其当前的功能,从显示 WAV 的波形开始。文件。为此,我需要从 WAV 中检索振幅与样本的关系。文件。鉴于我已经有一个记录文件,我怎么能快速进行?

谢谢!

最佳答案

AudioToolBox满足你的需要。
您可以使用 AudioFileService从音频文件中获取音频样本,例如 WAV文件,
然后您可以从每个样本中获得幅度。

 // this is your desired amplitude data
 public internal(set) var packetsX = [Data]()

 public required init(src path: URL) throws {
        Utility.check(error:  AudioFileOpenURL(path as CFURL, .readPermission, 0,  &playbackFile) ,                // set on output to the AudioFileID
                      operation: "AudioFileOpenURL failed")
        
        guard let file = playbackFile else {
            return
        }
        
        var numPacketsToRead: UInt32 = 0
        
        
        GetPropertyValue(val: &numPacketsToRead, file: file, prop: kAudioFilePropertyAudioDataPacketCount)
        
        var asbdFormat = AudioStreamBasicDescription()
        GetPropertyValue(val: &asbdFormat, file: file, prop: kAudioFilePropertyDataFormat)
        
        dataFormatD = AVAudioFormat(streamDescription: &asbdFormat)
        /// At this point we should definitely have a data format
        var bytesRead: UInt32 = 0
        GetPropertyValue(val: &bytesRead, file: file, prop: kAudioFilePropertyAudioDataByteCount)
        
        
        
        
        guard let dataFormat = dataFormatD else {
            return
        }
        
    
        let format = dataFormat.streamDescription.pointee
        let bytesPerPacket = Int(format.mBytesPerPacket)
        
        for i in 0 ..< Int(numPacketsToRead) {
            
            var packetSize = UInt32(bytesPerPacket)
                
            let packetStart = Int64(i * bytesPerPacket)
            let dataPt: UnsafeMutableRawPointer = malloc(MemoryLayout<UInt8>.size * bytesPerPacket)
            AudioFileReadBytes(file, false, packetStart, &packetSize, dataPt)
            let startPt = dataPt.bindMemory(to: UInt8.self, capacity: bytesPerPacket)
            let buffer = UnsafeBufferPointer(start: startPt, count: bytesPerPacket)
            let array = Array(buffer)
            packetsX.append(Data(array))
        }
        
        
        
    }
例如,WAV文件具有 channel 一、位深为 Int16 。
// buffer is of two Int8, to express an Int16
let buffer = UnsafeBufferPointer(start: startPt, count: bytesPerPacket)

更多信息,您可以查看my github repo

关于swift - 读取 WAV 文件并将其转换为 Swift 中的振幅数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28547968/

相关文章:

iOS swift UICollectionviewcell 快照错误

css - 创建一个 tumblr 主题 - 音频帖子不显示在博客上

audio - FFmpeg 输出不准确

speech-recognition - 编写软件以判断声音来自何处(定向聆听)

正弦波生成的C编程

ios - 如何在 iOS 推送通知后在除一个 View 之外的任何地方显示 UIAlertView

swift - 在 swift 中加载 UIWebView 中的 URL 时发生 fatal error

ios - 快速初始化的困惑

android - MediaControllerCompat-java.lang.IllegalArgumentException:错误的方向3

java - java中的音频波形已完成编码,但波形的读数不同