Created
January 18, 2021 10:08
-
-
Save fredriccliver/30ce44c7d19c05d36912d6f21d2d8bc6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ... | |
import CoreData | |
import AVFoundation | |
// ... | |
class ViewController: UIViewController { | |
// ... | |
var coreDataContext:NSManagedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext | |
// ... | |
func playPhraseSound(_ sentence:Sentence){ | |
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "AudioCache") | |
fetchRequest.predicate = NSPredicate(format: "remoteUrl = %@", sentence.soundUrl) | |
do { | |
let audioCaches = try self.coreDataContext.fetch(fetchRequest) | |
var playerItem:AVPlayerItem | |
if let audioCache = audioCaches.first as? AudioCache { | |
// There is cache on CoreData | |
playerItem = AVPlayerItem(asset: audioCache.data!.getAVAsset()) | |
} else { | |
// There isn't cache on CoreData | |
self.activityIndicatorView.startAnimating() | |
let newAudioCache = AudioCache(context: self.coreDataContext) | |
do{ | |
newAudioCache.remoteUrl = sentence.soundUrl | |
guard let url = URL.init(string: sentence.soundUrl) else { return } | |
newAudioCache.data = try! Data(contentsOf: url) | |
try self.coreDataContext.save() | |
} catch let err { | |
print("error on making audio cache", err) | |
} | |
playerItem = AVPlayerItem(asset: newAudioCache.data!.getAVAsset()) | |
} | |
player = AVPlayer.init(playerItem: playerItem) | |
} catch let err { | |
print("error on playing", err) | |
} | |
player?.play() | |
} | |
// ... | |
} | |
extension Data { | |
func getAVAsset() -> AVAsset { | |
let directory = NSTemporaryDirectory() | |
let fileName = "\(NSUUID().uuidString).wav" | |
let fullURL = NSURL.fileURL(withPathComponents: [directory, fileName]) | |
try! self.write(to: fullURL!) | |
let asset = AVAsset(url: fullURL!) | |
return asset | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment