【问题标题】:How can you play a sound of a specified duration using AVAudioPlayer on iOS?如何在 iOS 上使用 AVAudioPlayer 播放指定持续时间的声音?
【发布时间】:2011-07-03 16:57:51
【问题描述】:

我想在 IOS 的声音文件中播放指定的持续时间。我在 AVAudioPlayer 中找到了一种方法,该方法试图开始播放 (playAtTime:),但我找不到在声音文件结束之前指定结束时间的直接方法。

有没有办法做到这一点?

【问题讨论】:

    标签: iphone ios audio avaudioplayer playing


    【解决方案1】:

    如果您不需要太多精确度并且想坚持使用AVAudioPlayer,这是一种选择:

    - (void)playAtTime:(NSTimeInterval)time withDuration:(NSTimeInterval)duration {
        NSTimeInterval shortStartDelay = 0.01;
        NSTimeInterval now = player.deviceCurrentTime;
    
        [self.audioPlayer playAtTime:now + shortStartDelay];
        self.stopTimer = [NSTimer scheduledTimerWithTimeInterval:shortStartDelay + duration 
                                                          target:self 
                                                        selector:@selector(stopPlaying:)
                                                        userInfo:nil
                                                         repeats:NO];
    }
    
    - (void)stopPlaying:(NSTimer *)theTimer {
        [self.audioPlayer pause];
    }
    

    请记住,stopTimer 将在线程的运行循环中触发,因此音频播放时长会有所不同,具体取决于应用当时正在执行的其他操作。如果您需要更高级别的精度,请考虑使用AVPlayer 而不是AVAudioPlayerAVPlayer 播放AVPlayerItem 对象,让您指定forwardPlaybackEndTime

    【讨论】:

    • 感谢 AVPlayer。我以前不知道。
    • @cduhn 你会用什么来循环一个 f.e. 的声音。 10 秒长,但想继续播放 f.e.一分钟?
    • 哇!使用 AVPlayer 的音频版本比 AVAudioPlayer 具有明显的优势,尤其是在特定时间停止播放。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多