Audio Queue如何停止当前播放任务并立即开始播放另一个AudioQueueBuffer?

时间:2017-02-24 13:30:20

标签: ios audio audioqueue audioqueueservices

需要:我有一个音频队列和两个AudioQueueBuffer。我该怎么玩 NO.2 AudioQueueBuffer立即在NO AudioQueueBuffer中播放。 我尝试过AudioQueueStopAudioQueueReset。需要很长时间才能处理,NO AudioQueueBuffer打得太晚了。

-(void)playBuffer:(AudioBuffer *)buffer format:(const AudioStreamBasicDescription *)format
{
    AudioQueueStop(_audioQueue, YES);//this line consuming too much time
    AudioQueueDispose(_audioQueue, YES);
    AudioQueueRef newAudioQueue;
    AudioQueueBufferRef queueBuffer;
    AudioQueueNewOutput(format, audioQueueOutputCallback, (__bridge void*)self,
                        nil, nil, 0, &newAudioQueue);
    OSStatus status;
    status = AudioQueueAllocateBuffer(newAudioQueue, buffer->mDataByteSize, &queueBuffer);

    memcpy(queueBuffer->mAudioData, buffer->mData, buffer->mDataByteSize);
    queueBuffer->mAudioDataByteSize=buffer->mDataByteSize;
    status = AudioQueueEnqueueBuffer(newAudioQueue, queueBuffer, 0, NULL);

    Float32 gain=1.0;
    AudioQueueSetParameter(newAudioQueue, kAudioQueueParam_Volume, gain);
    AudioQueueStart(newAudioQueue, nil);
    AudioQueueFreeBuffer(newAudioQueue, queueBuffer);
    _audioQueue = newAudioQueue;
}

所以我的问题是:是否可以audio queue立即播放下一个音频缓冲区?或者audio queue是否与此任务不匹配而我需要替代方案吗?

1 个答案:

答案 0 :(得分:0)

最后我只是异步处理audioQueue。但我认为AVAudioUint对我的情况可能是一个更好的解决方案。

- (void)playBuffer:(AudioBuffer *)buffer format:(const AudioStreamBasicDescription *)format
{
    oldAudioQueue = _audioQueue;
    if (oldAudioQueue){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            AudioQueuePause(oldAudioQueue);
            //AudioQueueStop(oldAudioQueue, YES);//this line consuming too much time, will barries thread
            AudioQueueDispose(oldAudioQueue, YES);
            oldAudioQueue = nil;
        });
    }

    AudioQueueRef newAudioQueue;
    AudioQueueBufferRef queueBuffer;
    AudioQueueNewOutput(format, audioQueueOutputCallback, (__bridge void*)self,
                        nil, nil, 0, &newAudioQueue);

    OSStatus status;
    status = AudioQueueAllocateBuffer(newAudioQueue, buffer->mDataByteSize, &queueBuffer);

    memcpy(queueBuffer->mAudioData, buffer->mData, buffer->mDataByteSize);
    queueBuffer->mAudioDataByteSize=buffer->mDataByteSize;
    status = AudioQueueEnqueueBuffer(newAudioQueue, queueBuffer, 0, NULL);

    Float32 gain=1.0;
    AudioQueueSetParameter(newAudioQueue, kAudioQueueParam_Volume, gain);
    AudioQueueStart(newAudioQueue, nil);
    AudioQueueFreeBuffer(newAudioQueue, queueBuffer);
    _audioQueue = newAudioQueue;
}