.oga playback in swift - ios

I am trying to play an audio file with AVAudioPlayer with this code:
let urlString = "http://192.168.1.19:8080/download/2"
let url = URL(string: urlString)!
print("the url = \(url)")
do {
let data = try Data.init(contentsOf: url)
self.audioPlayer = try AVAudioPlayer.init(data: data)
self.audioPlayer.prepareToPlay()
self.audioPlayer.play()
} catch {
print("couldn't load file")
}
audio format is Oga (.oga) and it always failed to load. Any solution to play this .oga file?

Related

Read data from file swift

I was trying to read a file xyz.m4a and trying to play it. But I have an error
2018-04-24 18:11:20.010927+0530 Demo[10807:690526] NSURLConnection finished with error - code -1002
2018-04-24 18:11:20.327008+0530 Demo[10807:688427] CFURLCopyResourcePropertyForKey failed because it was passed an URL which has no scheme
Error: The file “xyz.m4a” couldn’t be opened.
Here is my code:
func audioMethod() {
let fileName = "xyz.m4a",
audioFile = getDocumentsURL().appendingPathComponent(fileName)
if !FileManager.default.fileExists(atPath: audioFile.path) {
print("We have no file !!!!!")
}
do {
let audioData = try Data(contentsOf: audioFile)
if audioPlayer == nil {
audioPlayer = try AVAudioPlayer.init(data: audioData, fileTypeHint: "m4a")
}
audioPlayer?.play()
} catch let error {
print("Error: " + error.localizedDescription)
}
}
func getDocumentsURL() -> URL {
let urlStr = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
let url = URL(string: urlStr!)
return url!
}
If I pass that URL direct in AVAudioPlayer as AVAudioPlayer.init(contentsOf: audioFile) then it works fine.
I have tried everything. But nothing works. Please let me know what is wrong with my code.
if let path = Bundle.main.path(forResource: "videoplayback", ofType: "mp4"){
let video = AVPlayer(url: URL(fileURLWithPath:path))
let videoPlayer = AVPlayerViewController()
videoPlayer.player = video
present(videoPlayer,animated: true,completion: {
video.play()
})
}
Add that Video in File Explorer
Then try with above code

AVAudioPlayer not playing m4a or mp3 filetype from a website

I am trying to locate a URL which is only pure .m4a sound with my application. I have the URL to the audio and theoretically download it. Then, with the downloaded fileURL to the sound, I try to play it with the AVAudioPlayer, yet it does not play any sound. Here is my code:
In the URL retrieval function, I call: (urls defined as a URL(string: url), url being the retrieve URL string)
downloadSound(url: urls!)
Here is my downloadSound() function:
func downloadSound(url:URL){
var downloadTask:URLSessionDownloadTask
downloadTask = URLSession.shared.downloadTask(with: url, completionHandler: { [weak self](URL, response, error) -> Void in
self?.playSound(url: URL!)
})
downloadTask.resume()
}
And lastly the playSound function:
func playSound(url:URL) {
print("The url is \(url)")
let player = try! AVAudioPlayer(contentsOf: url)
player.play()
Everything is being called as the print("The url is \(url)") returns me the path of the file (I am not actually able to track the file, however).
Here is the general path of the sound on the simulator:
file:///Users/[...]/Library/Developer/CoreSimulator/Devices/116C311A-C7F3-44EC-9762-2FAA0F9FE966/data/Containers/Data/Application/60BFCDE7-AC02-4196-8D1A-24EC646C4622/tmp/CFNetworkDownload_7VDpsV.tmp
Whereas running it on a phone returns:
file:///private/var/mobile/Containers/Data/Application/C75C1F1D-77E9-4795-9A38-3F0756D30547/tmp/CFNetworkDownload_T1XlPb.tmp
Thank you in advance.
I had the same problem and I choosed an alternative solution as app doc said:
A file URL for the temporary file. Because the file is temporary, you
must either open the file for reading or move it to a permanent
location in your app’s sandbox container directory before returning
from this delegate method.
The idea is just to copy from tmp directory to document directory and play from document directory.
Create a member variable:
var player = AVAudioPlayer()
Now implement your downloadSound method as below:
func downloadSound(url:URL){
let docUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let desURL = docUrl.appendingPathComponent("tmpsong.m4a")
var downloadTask:URLSessionDownloadTask
downloadTask = URLSession.shared.downloadTask(with: url, completionHandler: { [weak self](URLData, response, error) -> Void in
do{
let isFileFound:Bool? = FileManager.default.fileExists(atPath: desURL.path)
if isFileFound == true{
print(desURL) //delete tmpsong.m4a & copy
try FileManager.default.removeItem(atPath: desURL.path)
try FileManager.default.copyItem(at: URLData!, to: desURL)
} else {
try FileManager.default.copyItem(at: URLData!, to: desURL)
}
let sPlayer = try AVAudioPlayer(contentsOf: desURL!)
self?.player = sPlayer
self?.player.prepareToPlay()
self?.player.play()
}catch let err {
print(err.localizedDescription)
}
})
downloadTask.resume()
}
This is just a sample solution.

Audio Stream via firebase

I have uploaded some songs in firebase Storage directly,I just want to stream the song in AVAudioPlayer.
Below is the code which I am trying:
var mainRef: FIRStorageReference {
return FIRStorage.storage().reference(forURL: "gs://musicapp-d840c.appspot.com")
}
var audioStorageRef: FIRStorageReference{
return mainRef.child("SongsPath")
}
audioStorageRef.downloadURL { url, error in
if let error = error {
print(error.localizedDescription)
} else {
if let url = url {
do {
self.audioPlayer = try AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: String(describing: url)) as URL)
self.audioPlayer.play()
} catch {}
let storyboard = UIStoryboard(name: "AudioPlayer", bundle: nil)
let audioVc = storyboard.instantiateViewController(withIdentifier: "AudioPlayerViewController") as! AudioPlayerViewController
audioVc.playThisSong = String(describing: url)
self.present(audioVc, animated: false, completion: nil)
}
}
}
Here the song url from the firebase is passing but it is skipping the self.audioPlayer.play. ,I just want to stream the audio. Can I get a proper solution for this?
This is not an answer for streaming.
This is an answer for downloading the file, storing it locally, and playing the audio after the file has finished downloading.
Get a Firebase storage reference using a path string with the file extension. Get a file url to store it on the device using the same path string that we use for the Firebase storage reference.
Initiate the download task using write(toFile: URL). Store the download task in a variable to add observers. When the download is successful, play the audio.
In Swift 4:
var player: AVAudioPlayer?
let pathString = "SongsPath.mp3"
let storageReference = Storage.storage().reference().child(pathString)
let fileUrls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
guard let fileUrl = fileUrls.first?.appendingPathComponent(pathString) else {
return
}
let downloadTask = storageReference.write(toFile: fileUrl)
downloadTask.observe(.success) { _ in
do {
self.player = try AVAudioPlayer(contentsOf: fileUrl)
self.player?.prepareToPlay()
self.player?.play()
} catch let error {
print(error.localizedDescription)
}
}
This is minimal code. Implement error handling as you see fit.
Firebase example of downloading locally

Swift 3 Record audio and upload to Firebase storage and play back

I am making a chat room application, so far it is able to send message, image and video.
I am using a very similar method to send video and it works, but it's not working when sending audio.
The audio file and audio url is upload to Firebase successfully, But when I tried to play back the audio, it show this error: The operation couldn’t be completed. (OSStatus error 2003334207.).
The project is getting quite overwhelmingly large, and I have very little experience using AVAudio, so if you guys had similar problems before please teach me how to fix it. Thanks!!!
Here is the code of setting up the audioRecorder, and I get the url here and pass it to other func to put the audio file to Firebase storage.
func startRecording() {
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 12000,
AVNumberOfChannelsKey: 1,
AVEncoderAudioQualityKey: AVAudioQuality.low.rawValue
]
do {
let audioFileUrl = getAudiFileURL()
audioRecorder = try AVAudioRecorder(url: audioFileUrl, settings: settings)
audioRecorder.delegate = self
audioRecorder.record()
blackView.isHidden = false
} catch {
finishRecording(success: false)
}
}
Here is where I try to upload the audio file to Firebase storage, and it does print out the correct downloadURL. (The URL is pointing to the file's location in the iOS devices.)
func handleAudioSendWith(url: String) {
guard let fileUrl = URL(string: url) else {
return
}
let fileName = NSUUID().uuidString + ".m4a"
FIRStorage.storage().reference().child("message_voice").child(fileName).putFile(fileUrl, metadata: nil) { (metadata, error) in
if error != nil {
print(error ?? "error")
}
if let downloadUrl = metadata?.downloadURL()?.absoluteString {
print(downloadUrl)
let values: [String : Any] = ["audioUrl": downloadUrl]
self.sendMessageWith(properties: values)
}
}
}
Here is how I set up the url for the audioRecorder above.
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
func getAudiFileURL() -> URL {
return getDocumentsDirectory().appendingPathComponent(".m4a")
}
And this is where I play the audio:
func handleAudioPLay() {
if let audioUrl = message?.audioUrl, let url = URL(string: audioUrl) {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer?.delegate = self
audioPlayer?.prepareToPlay()
audioPlayer?.play()
print("Audio ready to play")
} catch let error {
print(error.localizedDescription)
}
}
}
I can actually download the sound file from Firebase using the url and play it on my computer, which means the url is fine.
I have solved the problem by downloading the sound file using URLSession, and play it using AVAudioPlayer(data: data!, fileTypeHint: "aac").

How to play audio sound file in local container in swift ios xcode

I need play audio sound file from user local file system container in iOS using Swift like
file:///Users/User/Library/Developer/CoreSimulator/Devices/EE8A846B-56D9-4B2B-9B52-FCC5CC16B7CA/data/Containers/Data/Application/C057C9A4-77DB-4615-AA78-C0A256ECD2D2/Documents/Dumont.mp3
Try This
//give your file path here in form of url
let urlstring = "file:///Users/User/Library/Developer/CoreSimulator/Devices/EE8A846B-56D9-4B2B-9B52-FCC5CC16B7CA/data/Containers/Data/Application/C057C9A4-77DB-4615-AA78-C0A256ECD2D2/Documents/Dumont.mp3"
let url = NSURL(string: urlstring)
do
{
self.player = try AVAudioPlayer(contentsOfURL: url)
player.prepareToPlay()
player.volume = 1.0
player.play()
}
catch let error as NSError
{
print(error.localizedDescription)
}
catch {
print("AVAudioPlayer init failed")
}

Resources