Turn Byte Array in Decimal Representation Data Into an Excecutable

Viewed 27

So, in my server I have data I got from an API whose contents look like this, it is an mp3 file.

210, 107, 180, 171, 213, 120, 193, 203, 10, 254, 198, 165, 46, 178, 201, 97, 205, 122, 30, 135, 212, 173, 59, 201, 66, 153, 112, 64, 104, 92, 85, 105, 8, 128, 213, 233, 136, 130, 57, 226, 129, 162, 48, 224, 17, 193, 128, 20, 171, 17, 158, 7, 15, 12, 24, 128, 113, 129, 135, 3, 3, 76, 36, 32, 198, 192, 204, 44, 104, 18, 20, 97, 1, 36, 129, 196, 64, 132, 160

and so on...

In the server I can take that data and write it into the file system as an mp3... but when I send that data to my client (Swift iOS) I get an mp3 file that does not play and when opened in a text editor the same numbers appear, instead of making it an executable audio mp3 file.

Here is how I implemented that:

func getAudioRawData() async throws {
    guard let url = URL(string: "http://192.168.1.104:8080/audio") else { fatalError("Missing URL") }
        let urlRequest = URLRequest(url: url)
    let (data, response) = try await URLSession.shared.data(for: urlRequest)
    
    guard (response as? HTTPURLResponse)?.statusCode == 200 else { fatalError("Error while fetching data") }
    print("Async audio", data)
    //IMPORTANT LINE ----->>>>>> print(writeToFile(data: data, fileName: "output")); <<<<<
    
}


func writeToFile(data: Data, fileName: String) -> URL? {
    // get path of directory
    guard let directory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else {
        return nil
    }
    // create file url
    let fileurl =  directory.appendingPathComponent("\(fileName).mp3")
// if file exists then write data
    if FileManager.default.fileExists(atPath: fileurl.path) {
        if let fileHandle = FileHandle(forWritingAtPath: fileurl.path) {
            // seekToEndOfFile, writes data at the last of file(appends not override)
            fileHandle.seekToEndOfFile()
            fileHandle.write(data)
            fileHandle.closeFile()
        }
        else {
            print("Can't open file to write.")
        }
    }
    else {
        // if file does not exist write data for the first time
        do{
            try data.write(to: fileurl, options: .atomic)
        }catch {
            print("Unable to write in new file.")
        }
    }
    return directory
}

SO the directory does return and the file is written, therefore my code has no errors as it does what I tell it to, but I don't know hoe to tell it to make that data into something an mp3 file can read and execute.

0 Answers
Related