I'm new to Swift from Objective-C and have hit a wall. I need to extract audio from a .mov file so I can then run this through speech to text processing. The code I have so far creates a file but it does not contain audio. This is the code I have so far
private var audioFilePath: URL!
private func createAudioFile(){
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
self.audioFilePath = url.appendingPathComponent("myAudio.m4a")
let theAsset = AVAsset(url: self.outputFilePath)
let exporter = AVAssetExportSession(asset: theAsset, presetName: AVAssetExportPresetHighestQuality)
exporter?.outputURL = self.audioFilePath
exporter?.outputFileType = AVFileTypeMPEG4
print("file path = ", self.audioFilePath)
exporter?.exportAsynchronously(completionHandler: {
print("exporter?.status\(exporter?.status)")
})
}
Thanks for your help!
Related
I have a .glb file in document folder, how do I get the image and load into scnScene? like how I load a uiimage from document folder
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first
{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("Image2.png")
let image = UIImage(contentsOfFile: imageURL.path
is it possible to load .glb in SCNScene?
let scene = SCNScene(named: "latest.glb")
answering my own question, I used GLTFSceneKit
let path = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask)[0]
.appendingPathComponent("test.glb")
var scene: SCNScene
do {
let sceneSource = try GLTFSceneSource(url: path)
scene = try sceneSource.scene()
} catch {
print("\(error.localizedDescription)")
return
}
Downloading an mp3 and saving it into the Library/caches folder works, But accessing it later doesn't.
Checking if the song really exists, i opened up Finder and went to the simulator folders. and my folder looks like this:
My song is located at: Library/Caches/Digger/Flower.mp3
Trying to access this using AVPlayer:
let folderName = "Digger"
let fileName = "Flower.mp3"
let url = FileManager.default
.urls(for: .cachesDirectory, in: .userDomainMask)[0]
.appendingPathComponent(folderName).appendingPathComponent(fileName)
var urlString = url.absoluteString
print("MyPath: \(urlString)")
urlString.removeSubrange(urlString.range(of: "file://")!)
let player = AVPlayer(url: URL(string: urlString)!)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
player.play()
}
But it doesn't work.
Simulator screenshot upon runtime:
Your URL handling is incorrect.
Replace these lines:
var urlString = url.absoluteString
print("MyPath: \(urlString)")
urlString.removeSubrange(urlString.range(of: "file://")!)
let player = AVPlayer(url: URL(string: urlString)!)
with:
let player = AVPlayer(url: url)
url already is the URL that you need. No need to try to convert it in any way.
For reference, use url.path to convert a file URL into a path string. And if you need to create a URL from a path string, use URL(fileURLWithPath:), not URL(string:). Only use URL(string:) with a string that has a URL scheme such as file://, https://, etc.
i have created video Filter demo, i am apply video filter successfully while video is play but i am unable to save video to local path. in local only gray image saved.
Below is my sample
let finalpath = "(FileManager.default.finalCompositions)/composition(getTimeStamp).mp4"
let finalUrl = URL(fileURLWithPath: finalpath)
print("Final url :: (finalUrl)")
let movieURL = Bundle.main.url(forResource: "test", withExtension: "mp4")
let asset: AVURLAsset = AVURLAsset(url: movieURL!)
let asetTrack: AVAssetTrack = asset.tracks(withMediaType: AVMediaTypeVideo)[0]
let exportedMovieFile = try! MovieInput(url: movieURL!, playAtActualSpeed: false)
exportedMovieFile.runBenchmark = true
let exportfilter = BrightnessAdjustment()
exportfilter.brightness = 0.5
exportedMovieFile.addTarget(exportfilter)
let exportedMovieWritter = try! MovieOutput(URL: finalUrl, size: Size(width: Float(asetTrack.naturalSize.width), height: Float(asetTrack.naturalSize.height)))
exportfilter.addTarget(exportedMovieWritter)
//Configure this for video from the movie file, where we want to preserve all video frames and audio samples
exportedMovieWritter.startRecording()
exportedMovieFile.start()
exportedMovieWritter.finishRecording {
exportfilter.removeAllTargets()
exportedMovieFile.removeAllTargets()
}
In swift how can I get the file path for a test audio File that i have copied into the resources folder in Xcode
The code I have gives file not found. Am I looking in the right Directories with NSSearchPathForDirectoriesInDomains? Any help much appreciated!
let name = "test.wav"
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let filePath = paths.stringByAppendingPathComponent(name)
let checkValidation = NSFileManager.defaultManager()
if (checkValidation.fileExistsAtPath(filePath)) {
print("found .wav")
} else {
print("file not found")
}
i just found this that works.
let name = "test.wav"
let soundPath = (NSBundle.mainBundle().resourcePath! as NSString).stringByAppendingPathComponent(name)
let soundURL = NSURL.fileURLWithPath(soundPath)
I have recorded audio in .AAC format using microphone and successfully saved in document directory.When i try to play particular recorded audio it is not playing but play methods are calling,Am not getting any sound in microphone . If any one can help me to figure out this issue
Recording Audio sample code below
func record() {
self.prepareToRecord()
if let recorder = self.audioRecorder {
recorder.record()
}
}
func prepareToRecord() {
let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let currentDateTime = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "ddMMyyyy-HHmmss"
str_Recordedname = formatter.stringFromDate(currentDateTime)+".AAC"
let pathArray = [dirPath, str_Recordedname]
let filePath = NSURL.fileURLWithPathComponents(pathArray)
print(filePath)
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 44100.0,
AVNumberOfChannelsKey: 2 as NSNumber,
AVEncoderAudioQualityKey: AVAudioQuality.High.rawValue
]
do
{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
self.audioRecorder = try AVAudioRecorder(URL:filePath!, settings:[:])
self.audioRecorder!.meteringEnabled = true
self.audioRecorder!.prepareToRecord()
self.audioRecorder!.record()
self.audioRecorder!.delegate = self
print("Recorded Audio is",filePath!)
}
catch let error as NSError
{
print(error.description)
}
}
Playing Sample code is
var filePath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
print("\nfilePath: \(filePath)")
filePath = filePath.stringByAppendingPathComponent(self.str_Recordedname)
print("\nfilePath: \(filePath)")
let filePathURL = NSURL.fileURLWithPath(filePath as String)
print("\nfilePathURL: \(filePathURL)")
do {
var player = AVPlayer()
let asset = AVURLAsset(URL: filePathURL)
let playerItem = AVPlayerItem(asset: asset)
player = AVPlayer(playerItem: playerItem)
player.play()
} catch let error as NSError {
print("Error: ", error.localizedDescription)
}
Thanks in Advance
Edit:
Removed AVPlayer Variable from Locally and pasted Globally its worked