Home > Software design >  Mp3 audio is not playing in swift
Mp3 audio is not playing in swift

Time:10-19

this is my swift class

import Foundation
import AVFoundation

class MusicPlayer{
    static let shared  = MusicPlayer()
    var audioPlayer: AVAudioPlayer?
    
    func startBackgroundMusic(backgroundMusicFileName: String) {
        if let bundle = Bundle.main.path(forResource: backgroundMusicFileName, ofType: "mp3") {
            let backgroundMusic = NSURL(fileURLWithPath: bundle)
            do {
                audioPlayer = try AVAudioPlayer(contentsOf:backgroundMusic as URL)
                guard let audioPlayer = audioPlayer else { return }
                audioPlayer.numberOfLoops = -1
                audioPlayer.volume = 1.0
                audioPlayer.prepareToPlay()
                audioPlayer.play()
            } catch {
                print(error)
            }
        }
    }
    
    func stopBackgroundMusic() {
        guard let audioPlayer = audioPlayer else { return }
        audioPlayer.stop()
    }
}

And, here is my code for the Controller class

func downloadUsingAlamofire() {
        let audioUrl =  URL(string:"https://www.learningcontainer.com/wp-content/uploads/2020/02/Kalimba.mp3")
        let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
        Alamofire.download(
            audioUrl!,
            method: .get,
            parameters: nil,
            encoding: URLEncoding.default,
            headers: nil,
            to: destination).downloadProgress(closure: { (progress) in
            }).response(completionHandler: { (DefaultDownloadResponse) in
                let imageURL = fetchPathinDirectory(filepath:audioUrl!.lastPathComponent)
                MusicPlayer.shared.startBackgroundMusic(backgroundMusicFileName: imageURL.path)
                
            })
    }

CodePudding user response:

As explain in comment ;

let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)

That means the file is downloaded in documents directory of your app. But when you read the file :

 if let bundle = Bundle.main.path(forResource: backgroundMusicFileName, ofType: "mp3") {
    let backgroundMusic = NSURL(fileURLWithPath: bundle)

You read for file in application bundle which is where your application and its ressources (storyboard, xib, …) are installed. You must read the file from documents directory. Something like :

var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let downloadedFileUrl = documentsURL.appendingPathComponent(backgroundMusicFileName)
  • Related