我们对应用程序的要求与 OP 描述的相同,并且遇到了相同的问题(即,如果用户想听她录制的内容,则必须停止而不是暂停录制观点)。我们的应用程序 (project's Github repo) 使用 AVQueuePlayer 进行播放,并使用类似于 kermitology's answer 的方法连接部分录音,但有一些显着差异:
- 在 Swift 中实现
- 将多个录音合并为一个
-
不要弄乱曲目
最后一项背后的基本原理是 AVAudioRecorder 的简单录音将只有一个轨道,而整个解决方法的主要原因是将这些单一轨道连接到资产中(参见 附录 3 )。那么为什么不改用AVMutableComposition 的insertTimeRange 方法,它采用AVAsset 而不是AVAssetTrack?
相关部分:(full code)
import UIKit
import AVFoundation
class RecordViewController: UIViewController {
/* App allows volunteers to record newspaper articles for the
blind and print-impaired, hence the name.
*/
var articleChunks = [AVURLAsset]()
func concatChunks() {
let composition = AVMutableComposition()
/* `CMTimeRange` to store total duration and know when to
insert subsequent assets.
*/
var insertAt = CMTimeRange(start: kCMTimeZero, end: kCMTimeZero)
repeat {
let asset = self.articleChunks.removeFirst()
let assetTimeRange =
CMTimeRange(start: kCMTimeZero, end: asset.duration)
do {
try composition.insertTimeRange(assetTimeRange,
of: asset,
at: insertAt.end)
} catch {
NSLog("Unable to compose asset track.")
}
let nextDuration = insertAt.duration + assetTimeRange.duration
insertAt = CMTimeRange(start: kCMTimeZero, duration: nextDuration)
} while self.articleChunks.count != 0
let exportSession =
AVAssetExportSession(
asset: composition,
presetName: AVAssetExportPresetAppleM4A)
exportSession?.outputFileType = AVFileType.m4a
exportSession?.outputURL = /* create URL for output */
// exportSession?.metadata = ...
exportSession?.exportAsynchronously {
switch exportSession?.status {
case .unknown?: break
case .waiting?: break
case .exporting?: break
case .completed?: break
case .failed?: break
case .cancelled?: break
case .none: break
}
}
/* Clean up (delete partial recordings, etc.) */
}
这张图帮助我了解了期望什么以及从哪里继承的问题。 (NSObject 隐含为没有继承箭头的超类。)
附录 1: 我对 switch 部分而不是在 AVAssetExportSessionStatus 上使用 KVO 持保留意见,但文档很清楚 exportAsynchronously 的回调块“在编写时被调用已完成或在写入失败的情况下”。
附录2:以防万一有人对AVQueuePlayer有问题:'An AVPlayerItem cannot be associated with more than one instance of AVPlayer'
附录 3: 除非您以立体声录制,但据我所知,移动设备只有一个输入。此外,使用精美的音频混合还需要使用AVCompositionTrack。一个好的 SO 线程:正确的AVAudioRecorder Settings for Recording Voice?