3
我必須合併音頻文件和錄製的語音。例如錄製的語音是47秒。我必須將4分鐘的音頻歌曲剪切或修剪至47秒。併合並音頻文件。iOS:用Swift修剪音頻文件?
var url:NSURL?
if self.audioRecorder != nil
{
url = self.audioRecorder!.url
}
else
{
url = self.soundFileURL!
}
print("playing \(url)")
do
{
self.newplayer = try AVPlayer(URL: url!)
let avAsset = AVURLAsset(URL: url!, options: nil)
print("\(avAsset)")
let audioDuration = avAsset.duration
let totalSeconds = CMTimeGetSeconds(audioDuration)
let hours = floor(totalSeconds/3600)
var minutes = floor(totalSeconds % 3600/60)
var seconds = floor(totalSeconds % 3600 % 60)
print("hours = \(hours),minutes = \(minutes),seconds = \(seconds)")}
這是輸出://小時= 0.0,分= 0.0,秒= 42.0
對於修剪方法我只是嘗試這樣做:如何設置確切持續時間,開始時間和結束時間和新網址:
func exportAsset(asset:AVAsset, fileName:String)
{
let documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let trimmedSoundFileURL = documentsDirectory.URLByAppendingPathComponent(fileName)
print("saving to \(trimmedSoundFileURL!.absoluteString)")
let filemanager = NSFileManager.defaultManager()
if filemanager.fileExistsAtPath(trimmedSoundFileURL!.absoluteString!) {
print("sound exists")
}
let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A)
exporter!.outputFileType = AVFileTypeAppleM4A
exporter!.outputURL = trimmedSoundFileURL
let duration = CMTimeGetSeconds(asset.duration)
if (duration < 5.0) {
print("sound is not long enough")
return
}
// e.g. the first 5 seconds
let startTime = CMTimeMake(0, 1)
let stopTime = CMTimeMake(5, 1)
let exportTimeRange = CMTimeRangeFromTimeToTime(startTime, stopTime)
exporter!.timeRange = exportTimeRange
// do it
exporter!.exportAsynchronouslyWithCompletionHandler({
switch exporter!.status {
case AVAssetExportSessionStatus.Failed:
print("export failed \(exporter!.error)")
case AVAssetExportSessionStatus.Cancelled:
print("export cancelled \(exporter!.error)")
default:
print("export complete")
}
})
}