'Playing a user's local audio file on macOS
I'm developing a music app of sorts for macOS with Swift. I would like to have the user select an audio file using a file picker, store that file/path, then play that file in-app. Right now I am able to get the file path from the picker dialog but I cannot play the file I get from that path (shown hardcoded here for concision) to play:
import Foundation
import AVFoundation
var audioPlayer = AVPlayer()
//These create the player from the web; they work as intended
//let audioSourceURL: String = "https://dl.espressif.com/dl/audio/ff-16b-2c-44100hz.mp3"
//let audioString: String = audioSourceURL
//let audioURL = URL(string: audioString)
//var playerItem = AVPlayerItem(url: audioURL!)
let laudioURL = URL(fileURLWithPath: "//Users/.../ThreeThing.mp3")
let isReachable = try? laudioURL.checkResourceIsReachable()
var playerItem = AVPlayerItem(url: laudioURL)
audioPlayer = AVPlayer(playerItem: playerItem)
audioPlayer.volume = 1
audioPlayer.play()
This method works when using the commented lines to retrieve a web file rather than a local one.
In a Swift playground, the laudioURL variable shows the mp3 file desired with extension. isReachable shows true. Neither is the case if I give an invalid file path. However, when accessing the playerItem, properties do not show, e.g., audioPlayer.currentItem?.duration.seconds returns nan—and the file doesn't play. I don't want to bundle the files into the app, as they're provided by the user. Is there an effective way to do this or an error in this method?
Solution 1:[1]
Have you try using AVAudioPlayer instead?
let laudioURL = URL(fileURLWithPath: "//Users/.../ThreeThing.mp3")
let audioPlayer = try? AVAudioPlayer(contentsOf: laudioURL, fileTypeHint: AVFileType.mp3.rawValue)
audioPlayer?.prepareToPlay()
audioPlayer?.play()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | bewithyou |