5

This is a follow-on question from my post about How to Encrypt mp3 Files in iOS.

How would I go about loading a track into an AVPlayerItem using NSData rather than a file path/URL?

Thanks

Community
  • 1
  • 1
Kiran Panesar
  • 3,094
  • 2
  • 22
  • 28

2 Answers2

9
[/*name of NSData*/ writeToFile:/*save file path*/ atomically: YES];
NSURL *filepath = [NSURL fileURLWithPath:/*save file path*/];
AVPlayerItem *player = [AVPlayerItem playerItemWithURL:filepath];

Untested, but should work.

Dustin
  • 6,783
  • 4
  • 36
  • 53
  • +1 for taking the time to provide an example. I was too lazy :) – Jeremy Aug 02 '12 at 15:20
  • Thanks for the example. I'm really hoping there's another way to do it because re-saving the MP3 in unencrypted form (even if it is only momentarily) presents a bit of a security issue, I think? – Kiran Panesar Aug 02 '12 at 15:47
  • It depends how secure your mp3 has to be... You can delete the file right after you're done if it's such a big deal. – Dustin Aug 02 '12 at 15:55
  • @Dustin Yeah, that's what I'm going to do. I'm sure it'll be more than secure enough, but it's not perfect. Thanks for your help :) – Kiran Panesar Aug 02 '12 at 16:03
  • 1
    For those who stumble upon this, AVAudioPlayer's `initWithData` method may be of help – danielmhanover Feb 16 '15 at 19:25
1

Updating Dustin's answer for Swift 5:

var audioData: Data // some audio data
var fileURL: URL // some local path, probably appending NSTemporaryDirectory() 
try! audioData.write(to: fileURL)
let item = AVPlayerItem(url: fileURL)
followben
  • 9,067
  • 4
  • 40
  • 42