python-pcm音频播放器

来源:互联网 发布:隐藏手机号打电话软件 编辑:程序博客网 时间:2024/05/24 11:14

50行pcm音频播放器

基于python、pysdl2的音频播放器:

  • 开发环境是ubuntu mate 16.04
  • 代码兼容python2、python3
  • 请安装pysdl2支持包
  • sudo apt install python-sdl2
  • 代码总共不到50行
  • 为在最短的代码下播放音频,目前仅支持pcm音频
  • 后续将支持更多格式

源代码

import sysimport ctypesfrom sdl2 import *class audio_ctx:  # Context    def __init__(self, fid, flag):        self.f = open(fid, 'rb')        self.runflag = flag    def __del__(self):        self.f.closedef audio_cb(udata, stream, len):    c = ctypes.cast(udata, ctypes.py_object).value    buf = c.f.read(2048)    if not buf:        SDL_PauseAudio(1)        c.runflag = 0        return    SDL_memset(stream, 0, len)    SDL_MixAudio(        stream, ctypes.cast(            buf, POINTER(ctypes.c_ubyte)), len, SDL_MIX_MAXVOLUME)def main():    print ("begin ...")    SDL_Init(0)    ctx = audio_ctx('piano.pcm', 1)    audiocallback = audio.SDL_AudioCallback(audio_cb)    reqspec = audio.SDL_AudioSpec(        44100, audio.AUDIO_U16SYS, 2, 1024, audiocallback, id(ctx))    spec = audio.SDL_AudioSpec(0, 0, 0, 0)  # nonsence    audio.SDL_OpenAudio(reqspec, ctypes.byref(spec))    SDL_PauseAudio(0)    while ctx.runflag:        SDL_Delay(1)    SDL_Quit()    print ("exit ...")    return 0if __name__ == "__main__":    sys.exit(main())

简介

  1. 网上有基于c语言版的pcm播放器,但是没有基于python版本,因此有此念头用python实现
  2. 代码力求python之美,优雅、简洁、高效
  3. 源码和样例音频请于以下github地址下载测试,一首优美的钢琴曲,正如python一样

github链接
https://github.com/mrcuck/py_audio_player

原创粉丝点击