首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用AVAssetReader播放声音

如何用AVAssetReader播放声音
EN

Stack Overflow用户
提问于 2012-01-16 18:15:05
回答 2查看 5.6K关注 0票数 2

我正在使用AVAssetReader从视频文件中获取各个帧。我想知道如何播放Mp4文件中的音频。

方法player play的返回值为false,所以没有声音可以播放,但是为什么呢

谢谢。

创建AVAssetReader

代码语言:javascript
复制
  NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"zhang" ofType:@"mp4"]];
    AVURLAsset *avasset = [[AVURLAsset alloc] initWithURL:url options:nil];
    AVAssetTrack *track1 = [[avasset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];

NSMutableDictionary *dic2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,  [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
                             [NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,
                             [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
                             [NSNumber numberWithBool:NO],AVLinearPCMIsNonInterleaved, nil]; 

output1 = [[AVAssetReaderTrackOutput alloc] initWithTrack:track1 outputSettings:dic2];

AVAssetReader *reader = [[AVAssetReader alloc] initWithAsset:avasset error:nil];

[reader addOutput:output1];
[reader startReading];

输出代码如下:

代码语言:javascript
复制
  CMSampleBufferRef sample = [output1 copyNextSampleBuffer];
    CMBlockBufferRef blockBufferRef = CMSampleBufferGetDataBuffer(sample);

    size_t length = CMBlockBufferGetDataLength(blockBufferRef);
    UInt8 buffer[length];
    CMBlockBufferCopyDataBytes(blockBufferRef, 0, length, buffer);

    NSData * data = [[NSData alloc] initWithBytes:buffer length:length];
    NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [NSString stringWithFormat:@"%@/test.mp3", docDirPath];
    [data writeToFile:filePath atomically:YES];
    [data release];

    NSError *error;
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
    player.numberOfLoops = 0;
    [player play];
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-01-16 18:43:05

一种选择是避免使用AVAudioPlayer,而是使用您解码的PCM数据来填充AudioQueue以进行输出。

理想的方法是根据从源mp4文件创建的AVAsset的音频轨道创建一个AVComposition。该AVComposition (作为AVAsset的子类)可以在AVPlayer中使用,然后它将只为您播放音轨。

您不能简单地将PCM数据块写到一个扩展名为".mp3“的文件中--这是一种编码格式。AVAudioPlayer将在文件中查找特定的编码数据,而您编写的文件将是不兼容的,这就是为什么您会收到返回值false的原因。如果您打算将音频输出到文件中,请使用具有适当设置的AVAssetWriter。这可以写出为核心音频文件,以获得最大的性能。此步骤还可以将音频编码为另一种格式(例如,mp3或AAC),但是这将带来沉重的性能成本,并且很可能不适合实时回放。

票数 3
EN

Stack Overflow用户

发布于 2012-10-17 14:36:02

资产不能立即播放。需要使用键值观察来观察状态的值。请参考苹果的AVCam示例。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8878524

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档