Here is my response:
Heritage Point1: [
Audio: "https://firebasestorage.googleapis.com/v0/b/sweetwalk-192506.appspot.com/o/Heritage%20Point1%2FAudios%2Fsmstreet1.mp3?alt=media&token=a3224b55-6039-4c6f-ac4e-78b9cf818c89"
CoverImage:"https://firebasestorage.googleapis.com/v0/b/sweetwalk-192506.appspot.com/o/Heritage%20Point1%2FImages%2Fsmstreet1.jpeg?alt=media&token=1acba6f0-8554-4b7e-828c-a7102c364d75"
Description: "none of the above"
]
Used AVFoundation Framework. I'm using Firebase, Xcode 9.2, Swift 4
Anyone please help me to play Audio from Firebase
You can use following code:
let audioUrlStr = "https://firebasestorage.googleapis.com/v0/b/sweetwalk-192506.appspot.com/o/Heritage%20Point1%2FAudios%2Fsmstreet1.mp3?alt=media&token=a3224b55-6039-4c6f-ac4e-78b9cf818c89"
if let url = URL(string: audioUrlStr) {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
self.audioPlayer = try AVAudioPlayer(data: Data(contentsOf: url))
self.audioPlayer!.delegate = self
self.audioPlayer!.volume = 2.0
self.audioPlayer!.prepareToPlay()
print("Audio ready to play")
self.audioPlayer!.play()
} catch let error {
print("error occured while audio downloading")
print(error.localizedDescription)
}
}
Related
I finally started learning to play sounds but I'm not succeeding in playing sounds in my app. I'm still on Xcode 10.1/Swift4 (not 4.2) as I'm not able to upgrade to Mojave/Catalina yet.
I read quite a few posts about .setCategory(.playback, mode: .default) carrying a bug in Xcode 10.1 but solutions found are for Swift 4.2. Also category: and mode:are expected to be of type String,but on docs the function is explained as:
func setCategory(_ category: AVAudioSession.Category, mode:
AVAudioSession.Mode, options: AVAudioSession.CategoryOptions = [])
throws
and they're not of type String. I'm a bit lost here.
My code doesn't throw any compiling error, but at runtime on console I get :
AVAudioSessionUtilities.mm:106:getUInt32: -- Category Value Converter
failed to find a match for string "ambient"
What am I missing here? Can you please point me in the right direction to understand this category problem?
As always thank you very much for your time and help.
This is the function that should play sounds :
static func playOnceSound(soundToPlay: String) {
var player: AVAudioPlayer?
guard let url = Bundle.main.url(forResource: soundToPlay, withExtension: "mp3") else { return }
do {
// try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default) // Error: Type 'String' has no member 'playback'
try AVAudioSession.sharedInstance().setCategory("ambient", mode: "default", options: .defaultToSpeaker)
try AVAudioSession.sharedInstance().setActive(true)
/* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */
guard let player = player else { return }
player.numberOfLoops = 1
player.volume = 1.0
player.play()
} catch let error {
print(error.localizedDescription)
}
}
Have you tried inputting ambient & default this way, instead of using a string? Also, instantiating the audio session object before setCategory:
var audioSession: AVAudioSession?
func setup() {
audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSession.Category.ambient, mode: .default, options: .defaultToSpeaker)
try audioSession.setActive(true)
}
catch {
print("Failed to set category", error.localizedDescription)
}
}
#IBAction func doPlay1(_ sender: AnyObject) {
do{
self.audioPlayer = try AVAudioPlayer(contentsOf: URL.init(string: url)!)
self.audioPlayer.prepareToPlay()
self.audioPlayer.delegate = self
self.audioPlayer.play()
}catch{
print(error.localizedDescription)
}
}
So I just set it in AppDelegate didFinishLaunchingWithOptions as :
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch let error1 as NSError{
error = error1
print("could not set session. err:\(error!.localizedDescription)")
}
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch let error1 as NSError{
error = error1
print("could not active session. err:\(error!.localizedDescription)")
}
and rewrote the function as :
static func playOnceSound(soundToPlay: String) {
if Sounds.player!.isPlaying == true {
Sounds.player!.stop()
}
let url = URL(fileURLWithPath: Bundle.main.path(forResource: soundToPlay, ofType: "mp3")!)
var error: NSError?
do {
Sounds.player = try AVAudioPlayer(contentsOf: url)
} catch let error1 as NSError {
error = error1
Sounds.player = nil
}
if let err = error {
print("audioPlayer error \(err.localizedDescription)")
return
} else {
Sounds.player!.prepareToPlay()
}
//negative number means loop infinity
Sounds.player!.numberOfLoops = 0
Sounds.player!.volume = Sounds.volume
Sounds.player!.play()
}
Thanks for your help, and I hope this will be of help to others.
Cheers.
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?
I have 2 variant of audio file, first embedded, second which I download from server.
First varian is work well.
But when I get audio file from server is not playing and get error.
I get path:
file:///var/mobile/Containers/Data/Application/24656EA9-6F1F-4C0F-A6FE-5D457908A80D/Documents/Dumont.mp3
And trying to play
func playMusic(filename: String) {
let url = NSBundle.mainBundle().URLForResource(filename, withExtension: "mp3")
guard let newURL = url else {
print("Could not find file: \(filename)")
return
}
do {
player = try AVAudioPlayer(contentsOfURL: newURL)
player!.numberOfLoops = -1
player!.prepareToPlay()
player!.play()
} catch let error as NSError {
print(error.description)
}
}
How to play this audio file in swift 2.3?
Platform iOS >8., Swift 2.3
Hey stupid guys who downvote answer for you:
if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent("Dumont.mp3")
do {
player = try AVAudioPlayer(contentsOfURL: path)
player!.numberOfLoops = -1
player!.prepareToPlay()
player!.play()
} catch let error as NSError {
print(error.description)
}
This code play downloaded song!
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").
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")
}