我能够使用 AVFoundation 录制和播放作品。问题是我得到了一个自定义的作品音频文件,如下所示:
| header 1 (1 byte) | opus data 1 (1~255 bytes) | header 2 (1 byte) | opus data 2 (1~255 bytes) | ... | ... |
每个标头指示作品数据的大小,即如果标头 1 为 200 (Int),则作品数据 1 为 200 字节
因此,我正在提取作品数据并附加到数据缓冲区,如下所示:
guard let url = Bundle.main.url(forResource: "test_16kbps", withExtension: "opus") else { return }
do {
let fileData = try Data(contentsOf: url)
while index < fileData.count {
headerData = fileData[index...(index + HEADER_SIZE)]
let opusBytesFromHeader = Int([UInt8](headerData)[0])
start = index + HEADER_SIZE
end = start + opusBytesFromHeader
opusData = fileData[start..<end]
opusAudioData.append(opusData)
index += (HEADER_SIZE + opusBytesFromHeader)
}
} catch let err {
print(err)
}
然后我尝试使用 AVAudioPlayer 播放如下
// ... ... ...
playData(audioData: opusAudioData)
// ... ... ...
func playData(audioData: Data){
var avAudioPlayer: AVAudioPlayer?
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
avAudioPlayer = try AVAudioPlayer.init(data: audioData)
if let player = avAudioPlayer {
player.play()
} else {
print("failed to create player from data")
}
} catch let error {
print(error.localizedDescription)
}
}
给出错误:The operation couldn’t be completed. (OSStatus error 1954115647.)
我还尝试了 MobileVLCKit pod,如下所示:
if let opusFilePath = createNewDirPath() { // creates "foo.opus"
do {
try opusAudioData.write(to: opusFilePath)
let opusMedia = VLCMedia(url: opusFilePath)
vlcPlayer.media = opusMedia
vlcPlayer.play()
} catch let err {
print(err)
}
}
给出以下错误:
2020-01-05 14:03:41.421270+0900 AppPlay[8695:4077367] creating player instance using shared library
[mp3 @ 0x10881e600] Failed to read frame size: Could not seek to 40126.
TagLib: Ogg::File::packet() -- Could not find the requested packet.
TagLib: Opus::File::read() -- invalid Opus identification header
Android 团队能够使用 libopus (JNI) 和 AudioTrack 进行游戏。因此,我尝试使用OpusKit pod 解码 opus 数据,如下所示:
if let decoded = OpusKit.shared.decodeData(opusData) {
decodedOpusData.append(decoded)
} else {
print("failed to decode")
}
然后尝试decodedOpusData使用 AVAudioPlayer 播放,但给出了同样的错误:The operation couldn’t be completed. (OSStatus error 1954115647.)。
我不知道如何播放该音频文件(我是 opus 新手)。
关于作品数据
样品:16000 | 帧大小:320(16 * 20 毫秒)| 频道:1