Comment puis-je générer un tableau de flottants à partir d'un file audio dans Swift

Je voudrais charger des files audio mp3 et wav comme des arrays de flottants ou doubles, semblable à la fonction io.wavfile.read dans scipy. Je peux le faire avec des données de microphone ou en jouant de l'audio en écrivant le stream audio dans un tampon. Cependant, je ne suis pas sûr de savoir comment charger toutes datatables d'un file audio à la fois.

— Mettre à jour

Pour toute personne travaillant avec des données de signal audio à l'avenir, voici une fonction qui fait l'affaire. C'est basé sur la réponse de Rhythmic Fistman.

func loadAudioSignal(audioURL: NSURL) -> (signal: [Float], rate: Double, frameCount: Int) { let file = try! AVAudioFile(forReading: audioURL) let format = AVAudioFormat(commonFormat: .PCMFormatFloat32, sampleRate: file.fileFormat.sampleRate, channels: file.fileFormat.channelCount, interleaved: false) let buf = AVAudioPCMBuffer(PCMFormat: format, frameCapacity: UInt32(file.length)) try! file.readIntoBuffer(buf) // You probably want better error handling let floatArray = Array(UnsafeBufferPointer(start: buf.floatChannelData[0], count:Int(buf.frameLength))) return (signal: floatArray, rate: file.fileFormat.sampleRate, frameCount: Int(file.length)) } 

AVAudioFile embedded à iOS (et OS X), est très pratique et fera également des conversions de format pour vous:

 import AVFoundation // ... let url = NSBundle.mainBundle().URLForResource("your audio file", withExtension: "wav") let file = try! AVAudioFile(forReading: url!) let format = AVAudioFormat(commonFormat: .PCMFormatFloat32, sampleRate: file.fileFormat.sampleRate, channels: 1, interleaved: false) let buf = AVAudioPCMBuffer(PCMFormat: format, frameCapacity: 1024) try! file.readIntoBuffer(buf) // this makes a copy, you might not want that let floatArray = Array(UnsafeBufferPointer(start: buf.floatChannelData[0], count:Int(buf.frameLength))) print("floatArray \(floatArray)\n") 

Malheureusement, pour les doubles, il ne semble pas suffisant de replace .PCMFormatFloat32 par .PCMFormatFloat64 car AVAudioPCMBuffer n'a pas de méthode float64ChannelData .

mettre à jour parce que je ne connais pas bien

Vous pouvez éviter de copyr le tableau en travaillant avec UnsafeBufferPointer , qui est un type de collection parfaitement bon:

 let floatArray = UnsafeBufferPointer(start: buf.floatChannelData[0], count:Int(buf.frameLength))