Есть ли у кого-нибудь фрагменты кода, которые показывают, как преобразовать файл M4a в WAV? Я знаю, что есть библиотеки, которые конвертируют наоборот.Код iOS для преобразования m4a в WAV
Спасибо.
Есть ли у кого-нибудь фрагменты кода, которые показывают, как преобразовать файл M4a в WAV? Я знаю, что есть библиотеки, которые конвертируют наоборот.Код iOS для преобразования m4a в WAV
Спасибо.
Если кто-то нуждается в какой-то код, чтобы сделать это здесь в Swift
func convertAudioFile(sourceURL: CFURLRef, destinationURL:
CFURLRef, outputFormat: OSType ,
outputSampleRate: Float64) -> OSStatus
{
var error : OSStatus = noErr
var destinationFile : ExtAudioFileRef = nil
var sourceFile : ExtAudioFileRef = nil
var srcFormat : AudioStreamBasicDescription = AudioStreamBasicDescription()
var dstFormat : AudioStreamBasicDescription = AudioStreamBasicDescription()
var audioConverter : AudioConverterRef = nil
audioConverter = AudioConverterRef.init()
ExtAudioFileOpenURL(sourceURL, &sourceFile)
var thePropertySize: UInt32 = UInt32(strideofValue(srcFormat))
ExtAudioFileGetProperty(sourceFile, kExtAudioFileProperty_FileDataFormat, &thePropertySize, &srcFormat)
dstFormat.mSampleRate = (outputSampleRate == 0 ? srcFormat.mSampleRate : outputSampleRate) //Set sample rate
dstFormat.mFormatID = outputFormat
dstFormat.mChannelsPerFrame = 1
dstFormat.mBitsPerChannel = 16
dstFormat.mBytesPerPacket = 2 * dstFormat.mChannelsPerFrame
dstFormat.mBytesPerFrame = 2 * dstFormat.mChannelsPerFrame
dstFormat.mFramesPerPacket = 1
dstFormat.mFormatFlags = kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagIsSignedInteger // little-endian
//Create destination file
ExtAudioFileCreateWithURL(destinationURL, kAudioFileCAFType, &dstFormat, nil,
AudioFileFlags.EraseFile.rawValue, &destinationFile)
ExtAudioFileSetProperty(sourceFile, kExtAudioFileProperty_ClientDataFormat, thePropertySize, &dstFormat)
ExtAudioFileSetProperty(destinationFile, kExtAudioFileProperty_ClientDataFormat, thePropertySize, &dstFormat)
var size : UInt32 = UInt32(strideofValue(audioConverter))
ExtAudioFileGetProperty(destinationFile, kExtAudioFileProperty_AudioConverter, &size, &audioConverter)
var canResume : UInt32 = 0
size = UInt32(strideofValue(canResume))
error = AudioConverterGetProperty(audioConverter, kAudioConverterPropertyCanResumeFromInterruption, &size, &canResume)
let bufferByteSize : UInt32 = 32768
var srcBuffer = [UInt8](count: 32768, repeatedValue: 0)
var sourceFrameOffset : ULONG = 0
print("Converting audio file")
while(true){
var fillBufList = AudioBufferList(
mNumberBuffers: 1,
mBuffers: AudioBuffer(
mNumberChannels: 2,
mDataByteSize: UInt32(srcBuffer.count),
mData: &srcBuffer
)
)
var numFrames : UInt32 = 0
if(dstFormat.mBytesPerFrame > 0){
numFrames = bufferByteSize/dstFormat.mBytesPerFrame
}
ExtAudioFileRead(sourceFile, &numFrames, &fillBufList)
if(numFrames == 0){
error = noErr;
break;
}
sourceFrameOffset += numFrames
error = ExtAudioFileWrite(destinationFile, numFrames, &fillBufList)
}
ExtAudioFileDispose(destinationFile)
ExtAudioFileDispose(sourceFile)
let audioAsset = AVURLAsset.init(URL: destinationURL, options: nil)
if(audioAsset.duration.seconds < 5.0){
error = -2500
}
return error;
AVAssetReader и AVAssetWriter в структуре AVFoundation могут использоваться для чтения файлов AAC и записи этих данных в виде файлов WAV/RIFF на устройствах iOS. На веб-сайте разработчика Apple есть образец кода. Это немного больше, чем короткий фрагмент.
Спасибо, что я сейчас работаю. Я конвертирую код в Swift, так как этот пример кода использует C++. – O2U
Вот редактировать на @ 2 † answere. Как и выше, код фактически не преобразует его в волновой файл. Пожалуйста, используйте «kAudioFileWAVEType» вместо «kAudioFileCAFType» в вышеприведенном коде в строке //Create destination file ExtAudioFileCreateWithURL(destinationURL, kAudioFileCAFType, &dstFormat, nil, AudioFileFlags.EraseFile.rawValue, &destinationFile)
Вы что-то изменили? Не задает destinationFile, когда я использую 'kAudioFileWAVEType' –
Нет, ничего не измените. Проверьте правильность вашего адресата или нет, это может быть проблемой в случае, если файл назначения не установлен. –
Просто обновление для Swift 3:
func convertAudio(_ url: URL, outputURL: URL) {
var error : OSStatus = noErr
var destinationFile: ExtAudioFileRef? = nil
var sourceFile : ExtAudioFileRef? = nil
var srcFormat : AudioStreamBasicDescription = AudioStreamBasicDescription()
var dstFormat : AudioStreamBasicDescription = AudioStreamBasicDescription()
ExtAudioFileOpenURL(url as CFURL, &sourceFile)
var thePropertySize: UInt32 = UInt32(MemoryLayout.stride(ofValue: srcFormat))
ExtAudioFileGetProperty(sourceFile!,
kExtAudioFileProperty_FileDataFormat,
&thePropertySize, &srcFormat)
dstFormat.mSampleRate = 44100 //Set sample rate
dstFormat.mFormatID = kAudioFormatLinearPCM
dstFormat.mChannelsPerFrame = 1
dstFormat.mBitsPerChannel = 16
dstFormat.mBytesPerPacket = 2 * dstFormat.mChannelsPerFrame
dstFormat.mBytesPerFrame = 2 * dstFormat.mChannelsPerFrame
dstFormat.mFramesPerPacket = 1
dstFormat.mFormatFlags = kLinearPCMFormatFlagIsPacked |
kAudioFormatFlagIsSignedInteger
// Create destination file
error = ExtAudioFileCreateWithURL(
outputURL as CFURL,
kAudioFileWAVEType,
&dstFormat,
nil,
AudioFileFlags.eraseFile.rawValue,
&destinationFile)
print("Error 1 in convertAudio: \(error.description)")
error = ExtAudioFileSetProperty(sourceFile!,
kExtAudioFileProperty_ClientDataFormat,
thePropertySize,
&dstFormat)
print("Error 2 in convertAudio: \(error.description)")
error = ExtAudioFileSetProperty(destinationFile!,
kExtAudioFileProperty_ClientDataFormat,
thePropertySize,
&dstFormat)
print("Error 3 in convertAudio: \(error.description)")
let bufferByteSize : UInt32 = 32768
var srcBuffer = [UInt8](repeating: 0, count: 32768)
var sourceFrameOffset : ULONG = 0
while(true){
var fillBufList = AudioBufferList(
mNumberBuffers: 1,
mBuffers: AudioBuffer(
mNumberChannels: 2,
mDataByteSize: UInt32(srcBuffer.count),
mData: &srcBuffer
)
)
var numFrames : UInt32 = 0
if(dstFormat.mBytesPerFrame > 0){
numFrames = bufferByteSize/dstFormat.mBytesPerFrame
}
error = ExtAudioFileRead(sourceFile!, &numFrames, &fillBufList)
print("Error 4 in convertAudio: \(error.description)")
if(numFrames == 0){
error = noErr;
break;
}
sourceFrameOffset += numFrames
error = ExtAudioFileWrite(destinationFile!, numFrames, &fillBufList)
print("Error 5 in convertAudio: \(error.description)")
}
error = ExtAudioFileDispose(destinationFile!)
print("Error 6 in convertAudio: \(error.description)")
error = ExtAudioFileDispose(sourceFile!)
print("Error 7 in convertAudio: \(error.description)")
}
Просто отлично! Спасибо! Хотел бы я проголосовать 10 раз. –
Есть ли другие изменения для экспорта в MP3, кроме использования kAudioFileMP3Type? Я получаю ничтожный сбой при ошибке = ExtAudioFileSetProperty (destinationFile !, при использовании типа MP3 – miOS
Возможно, вам придется попробовать разные mFormatFlags. Вы заметили, что это разница между этим и принятым ответом, отличным от kAudioFileMP3Type. – MScottWaller
увидеть этот раз может быть, это поможет вам http://stackoverflow.com/questions/31452202/ios-swift-merge-and-convert-wav-files-to-mp3 –