'How to convert to data and save an audio file

Updated Code - in the do block I am now using the below code , there is no error but is the approach correct ?

do {
                let input = try Data(contentsOf: songUrl)
                try input.write(to: songUrl)
                song.songFile = songUrl.path
                    }

I have audio files saved as sample1.mp3, sample2.mp3 up to sample5.mp3. I want the files to be saved to the documents directory of the app. I get the url and then save the url to coredata field called songFile, which I can later access and play the file in a music player.

I am trying the below code but I do not know how to convert the audio file (sample1.mp3etc) to Data. is the below code correct?

First the function for accession documents directory

func getDocumentsDirectory() -> URL {
  
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)

     
        return paths[0]
    }

Now an attempt to add these files to documents directory of app and get back the path, the line in do block is where I am unable to find a way to convert the audio file to data type. how can I do it?

for j in 1...5 {
    let song = Song(context: container.viewContext)
    song.songName = "Song\(j)"
    song.album = album
    song.isFavorite = false
    song.musicDirector = "Mr \(j)"
    song.singers = "Mr \(j) and Mrs \(j)"
    song.detail = "Its a song no \(j)"
    let songUrl = getDocumentsDirectory().appendingPathComponent("sample\(j).mp3")
   
    
    do {
        try "sample\(j).mp3".write(to: songUrl, atomically: true, encoding: .utf8) < —— is this line going to get me Data, if not how 
     
        song.songFile = songUrl.path
            } catch {
                print(error.localizedDescription)
            }
    }
}


Solution 1:[1]

The below solution worked when I added Bundle.main, the main part was as below, however, I will avoid this back and forth between core data and documents and bundle and will probably use the basic simple way of accessing the files from asset catalog and use them, as I do see a spike in memory needed for app … any ways it was good to know a new way of interesting code … if any one wants to suggest any changes please do , thanks

 let songUrl = getDocumentsDirectory().appendingPathComponent("sample\(j).mp3")
            guard let url = Bundle.main.url(forResource: "sample1", withExtension: "mp3") else { return }
            do {
                let input = try Data(contentsOf: url)

                try input.write(to: songUrl)
                song.songFile = songUrl.path
              
                
                
                    }

// Complete function

func createSampleData() throws {
        // ViewContext holds are the active objects in memory and only write
        // back to persistent store when we ask it to save.
        let viewContext = container.viewContext
        
        for i in 1...5 {
            let album = Album(context: viewContext)
            album.albumName = "Album \(i)"
            album.songs = []
            album.albumImage = UIImage(named: "music\(i)")?.jpegData(compressionQuality: 1.0)
            album.albumDetail = "The album has been given name Album -- \(i)"
        
        for j in 1...5 {
            let song = Song(context: container.viewContext)
            song.songName = "Song\(j)"
            song.album = album
            song.isFavorite = false
            song.musicDirector = "Mr \(j)"
            song.singers = "Mr \(j) and Mrs \(j)"
            song.detail = "Its a song no \(j)"
          //  let songUrl = getDocumentsDirectory().appendingPathComponent("sample\(j).mp3")
            let songUrl = getDocumentsDirectory().appendingPathComponent("sample\(j).mp3")
            guard let url = Bundle.main.url(forResource: "sample1", withExtension: "mp3") else { return }
            do {
                let input = try Data(contentsOf: url)

                try input.write(to: songUrl)
                song.songFile = songUrl.path
              
                
                
                    } catch {
                        print(error.localizedDescription)
                    }
            }
        }
        try viewContext.save()
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 multiverse