You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Love2D中播放音频文件的指定片段?

Love2D 播放音频指定片段实现方案

你可以根据使用场景选择以下两种实现方式:


方案1:实时控制播放进度

适合单次播放片段、不需要复用的场景,实现逻辑最简单:

  • 加载音频时优先选择static类型,小文件定位速度更快,无延迟
  • 播放前先定位到片段起始位置,再在love.update回调中监听播放进度,到达结束位置时停止播放即可
function love.load()
    -- 加载音频,static类型适合10MB以内的小音频
    local sound = love.audio.newSource('sound.wav', 'static')
    -- 定义片段的起止时间,单位为秒
    local startTime = 2.0 -- 从第2秒开始播放
    local endTime = 5.0 -- 播放到第5秒结束
    
    -- 定位到起始位置后播放
    sound:seek(startTime)
    sound:play()
end

function love.update(dt)
    if sound:isPlaying() then
        local currentPos = sound:tell()
        -- 到达结束时间就停止播放
        if currentPos >= endTime then
            sound:stop()
            -- 如果需要循环播放片段,可在这里重新seek到startTime再调用play
        end
    end
end

方案2:预裁剪生成音频片段对象

适合需要反复播放同一片段的场景,性能更好,不会有重复的进度判断开销:
通过SoundData接口提前截取对应时间区间的采样数据,生成独立的音频片段对象,直接调用play就只会播放指定片段

-- 封装裁剪音频片段的工具函数
function createAudioClip(sourcePath, startTime, endTime)
    local originData = love.sound.newSoundData(sourcePath)
    local sampleRate = originData:getSampleRate()
    local bitDepth = originData:getBitDepth()
    local channels = originData:getChannelCount()
    -- 计算起止采样点
    local startSample = math.floor(startTime * sampleRate)
    local endSample = math.floor(endTime * sampleRate)
    local clipSampleCount = endSample - startSample
    -- 创建新的SoundData存储片段数据
    local clipData = love.sound.newSoundData(clipSampleCount, sampleRate, bitDepth, channels)
    -- 拷贝对应区间的采样数据
    for i = 0, clipSampleCount - 1 do
        for channel = 1, channels do
            local sample = originData:getSample(startSample + i, channel)
            clipData:setSample(i, channel, sample)
        end
    end
    return love.audio.newSource(clipData)
end

-- 使用示例
function love.load()
    -- 直接生成2秒到5秒的音频片段对象
    local audioClip = createAudioClip('sound.wav', 2.0, 5.0)
    -- 调用play就只会播放截取的片段,不需要额外控制进度
    audioClip:play()
end

注意:如果你的音频是大文件,使用stream类型边加载边播放,方案1的seek操作会有轻微延迟,这种场景建议提前把需要截取的片段单独导出为独立音频文件使用。

内容的提问来源于stack exchange,提问作者user16999379

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 03:45:03