How to Retrieve Audio File from Parse Swift

how to retrieve audio file from parse swift

Checking the official documentation it should look something like this (I don't use Swift so please bear with me):

audioFile.getDataInBackgroundWithBlock{ (audioFile: NSData?, error:NSError?) -> Void in
if error == nil {
let path = "path-to-your-file"
if !audioFile.writeToFile(path, atomically: true){
print("Error saving")
}
}
}

I would recommend to go through some tutorials (e.g. here) where you might get better examples of file handling in Swift.

Update

Apparently both the block's parameters have to be optionals (see here). Your result block needs to be of type (audioFile: NSData?, error: NSError?)

how to upload recorded audio file to parse?

After this great tutorial at https://www.youtube.com/watch?v=4qj1piMAPE0 my solution was in Swift:

    let path = getCacheDirectory().stringByAppendingPathComponent(fileName)
let filePath = NSURL(fileURLWithPath: path)

var dataToUpload : NSData = NSData(contentsOfURL: filePath!)!

let soundFile = PFFile(name: fileName, data: dataToUpload)
var userSound = PFObject(className:"upload")
userSound["name"] = "Sara"
userSound["sound"] = soundFile
userSound.saveInBackground()

where getCacheDirectory() is a function used in the tutorial

Playing Audio From Parse.com

You are using the wrong method to get a NSURL here, you try to create a local file URL from an URL that points to a resource on a remote server.

Instead of NSURL(fileURLWithPath: audioPath) you should use the initalizer that accepts an URL string as the input (see here https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/#//apple_ref/occ/instm/NSURL/initWithString:)

Your current code would point to a local resource which does not exist on the local filesystem whereas it should point to the file on the Parse server.

Just as a reference, the difference between URLWithString and fileURLWithPath What is difference between URLWithString and fileURLWithPath of NSURL?

Playing music from parse in swift

I changed code this way.

    query.whereKeyExists("audio")
query.findObjectsInBackgroundWithBlock { (objects:[PFObject]?, error: NSError?) -> Void in
if error == nil {
let audio = objects?[0]
let audioFile = audio?["audio"] as? PFFile
audioFile?.getDataInBackgroundWithBlock({ (audio: NSData?, error: NSError?) -> Void in
if audio != nil {
do {
self.audioPlayer = try AVAudioPlayer(data: audio!)
self.audioPlayer.prepareToPlay()
self.audioPlayer.delegate = self
self.audioPlayer.volume = 10.0
self.audioPlayer.play()
} catch {
print("Error occured while playing music!")
}
} else {
print ("Somehow audio is nil!")
}
})
} else {
print("Error occured while downloading file!")
}
}

Value of 1.0 indicates full volume for the audio player but I was not able to hear it on simulator so I used 10.0. In the first case NSData was nil so I had to change that part of code and used getDataInBackgroundWithBlock. This method is parse method which finds objects asynchronously and calls the given block with the results. In the block NSData isn't nil anymore so AVAudioPlayer works normally.

Streaming audio from Parse.com – no data retrieved?

The problem that I was experiencing has mysteriously disappeared and I'm at a loss for what could have caused it. Although I might have received 0-bytes if there was an issue with the network on the machine that I was running the simulator on, no errors were logged.

But it does work. Another X-File, I suppose.

How to get Track Id from m4a audio file in swift 5.3

You've already got the track number in trackItems. However it should be a dataValue, not a stringValue.

For one of my tracks I see 8 bytes of what looks like 4 16bit big endian integers:

0x00000008000e0000

Mine is track 8 of 14, so I guess you want the 2nd integer.

Here's more anecdotal evidence of the above:

https://lists.apple.com/archives/cocoa-dev/2009/Oct/msg00952.html

You could do what you want using this (note the symbols for the keySpace/keys):

if let trackItem = AVMetadataItem.metadataItems(from: metadata, filteredByIdentifier: .iTunesMetadataTrackNumber).first,
let data = trackItem.dataValue,
data.count == 8 {
let bytes = [UInt8](data)
let trackNumber = ((Int)(bytes[2]) << 8) | (Int)(bytes[3])
let totalTracks = ((Int)(bytes[4]) << 8) | (Int)(bytes[5])
print("trackNumber: \(trackNumber)/\(totalTracks)")
}

N.B.: it's different for mp3/ID3 in which case you'll want id3/TRCK & it's a stringValue containing an integer.

Streaming audio from parse in Swift 3

I found out why I got the error. It's because some of the song names have spaces in them, but the first song doesn't have any spaces in its names. So I tried to copy the link in the browser and see how the browser deals with spaces. I found out it replaces spaces with %20.

So I replaced every space with "%20" and now it works.

Correct code

func grabSong() {        
let SongQuery = PFQuery(className: "Songs")
SongQuery.getObjectInBackground(withId:iDArray[SelectedSongNumber] ,block: { (object : PFObject?, error : Error?) -> Void in
if let AudioFileURLTemp : PFFile = object?.value(forKey: "SongFile") as? PFFile {
var songID = AudioFileURLTemp.url!.replacingOccurrences(of: " ", with: "%20")

audioP = AVPlayer(url: URL(string:songID)!)
audioP.play()
}
})
}


Related Topics



Leave a reply



Submit