4

I have successfully added https://github.com/chrisballinger/Opus-iOS to my project and I am able to call the functions declared in its header.

I want to convert from OPUS to AAC so my first step would be to decode my opus file. However, it keeps throwing an error code.

The file I am using is the 2-second file from https://people.xiph.org/~giles/2012/opus/.

This is my code

    let url = Bundle.main.url(forResource: "detodos", withExtension: "opus")
    print(url) //prints path correctly

    var bytes = [UInt8]()

    if let data = NSData(contentsOf: url!) {
        var buffer = [UInt8](repeating: 0, count: data.length)
        data.getBytes(&buffer, length: data.length)
        bytes = buffer

        let d = opus_decoder_create(48000, 1, nil)

        var sampleBuffer = [opus_int16](repeating: 0, count: data.length)

        print(opus_int32(bytes.count)) //6270

        let w = opus_decode(d!, bytes, opus_int32(bytes.count), &sampleBuffer, opus_int32(5760), opus_int32(1))
        print(sampleBuffer)   // [0,0,...] every time
        print(w)    //-4 every time
        //-4 = OPUS_INVALID_PACKET
    }

I would've guessed that in this very minimal implementation nothing should go wrong but apparently it does. Printing my bytes object returns tons of different numbers so I know for a fact it doesn't stay at all-0's.

I realized that it might be due to the method expecting pure "audio data" but the file also contains a header etc. How can I strip this off?

user2330482
  • 1,053
  • 2
  • 11
  • 19

1 Answers1

3

The opus library decodes Opus packets. You give it an Opus packet and it decodes it; one packet at a time. You are trying to give it an entire Ogg Opus file, including all of the headers, framing, tags, and other metadata.

The easiest way to decode an entire Ogg Opus file is with the opusfile library. It can even stream the data from a URL if you want, so that you don't have to download it all before you start decoding as you are doing here. Alternatively, instead of opusfile you could use the ogg library to extract packets from the file and then pass each audio packet to the opus library for decoding.

mark4o
  • 58,919
  • 18
  • 87
  • 102
  • Thanks for your answer. I have found this https://github.com/tyrone-sudeium/libopusfile-ios but it's 4 years old and doesn't compile well in a swift nor in an obj-c project. Have you by any chance ever used it or any alternatives to it? Thanks – user2330482 Feb 02 '18 at 01:14
  • I have used the opusfile library from C but not from Swift or Objective-C. – mark4o Feb 02 '18 at 05:53