derekli66 / Learning-Core-Audio-Swift-SampleCode

Swift sample code for the book, Learning Core Audio. The original sample code was written in C/Objective-C but I tried to make it in Swift version.
MIT License
156 stars 27 forks source link

Thank you #4

Closed little-dandan closed 4 years ago

little-dandan commented 4 years ago

Thank you: But there are new problems. output file duration is very short. You can open the compressed audio file, the sound content will play very fast, completely can not hear the content.

Originally posted by @little-dandan in https://github.com/derekli66/Learning-Core-Audio-Swift-SampleCode/issues/3#issuecomment-655322489

derekli66 commented 4 years ago

Hi @little-dandan,

The result is same as its original C version sample code. I didn't study it further to dig out why the wired result after conversion.

If you're really interesting in studying Core Audio low-level API, you can read the book, Learning Core Audio: A Hands-On Guide to Audio Programming for Mac and iOS and also download its original sample code. Or you may contact its authors for more helps.

Check the following link for further study. https://www.informit.com/store/learning-core-audio-a-hands-on-guide-to-audio-programming-9780321636843

If you want to use audio converter in production, you may consider using high level API, AVAudioConverter.

nbarnett commented 4 years ago

I'd like to add my thanks to @derekli66. I've been working through the "Learning Core Audio" book and using this repo as a reference for implementing the examples in Swift. It has been a valuable resource!

@little-dandan - I've also noticed the issue in the Chapter 6 Audio Converter where the output file is very short and when you try to play it back it sounds like it's skipping. I had a look at the documentation for AudioFileWritePackets and found that the 3rd parameter is inNumBytes, which is described as "The number of bytes of audio data being written". In the example code in the book, which @derekli66 has implemented here in Swift, they pass in ioOutputDataPackets for this parameter. I think that this is wrong because there are 4 bytes per packet, meaning that only ¼ of each buffer is being written to the file. I made the following change and the output file now sounds correct:

AudioFileWritePackets(
    mySettings.outputFile!,
    false,
    ioOutputDataPackets * mySettings.outputFormat.mBytesPerPacket,
    nil,
    Int64(outputFilePacketPosition / mySettings.outputFormat.mBytesPerPacket),
    &ioOutputDataPackets,
    convertedData[0].mData!
)
derekli66 commented 4 years ago

Thank you so much, @nbarnett. It really appreciate that you use your valuable time to help find out the error. You are correct. I will make an update in the sample code.