Click here to Skip to main content
15,867,835 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm converting MPMediaItem to NSData using below code, when I'm playing a song using NSData in Bluetooth speakers song not making clear sound. Its like this code may reduce song quality when converting to NSData.

So my question is how I maintain high quality song or any other way to get high quality NSData?

What I have tried:

func export(_ assetURL: URL, completionHandler: @escaping (_ fileURL: URL?, _ error: Error?) -> ()) {
    let asset = AVURLAsset(url: assetURL)
    guard let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A) else {
        completionHandler(nil, ExportError.unableToCreateExporter)
        return
    }

    let fileURL = URL(fileURLWithPath: NSTemporaryDirectory())
        .appendingPathComponent(NSUUID().uuidString)
        .appendingPathExtension("m4a")

    exporter.outputURL = fileURL
    exporter.outputFileType = "com.apple.m4a-audio"

    exporter.exportAsynchronously {
        if exporter.status == .completed {
            completionHandler(fileURL, nil)
        } else {
            completionHandler(nil, exporter.error)
        }
    }


}

func exampleUsage(with mediaItem: MPMediaItem, completionHandler : @escaping (_ songData:NSData?) -> ()) {
    if let assetURL = mediaItem.assetURL {
        export(assetURL) { fileURL, error in
            guard let fileURL = fileURL, error == nil else {
                print("export failed: \(error)")
                completionHandler(nil)
                return
            }

            // use fileURL of temporary file here
            print("Exported File : \(fileURL)")
            if let rawData = NSData(contentsOf: fileURL)
            {
                print("Exported File length : ",rawData.length)
                completionHandler(rawData)
            }
        }
    }
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900