免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1871 | 回复: 2
打印 上一主题 下一主题

python多线程问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-06-18 01:05 |只看该作者 |倒序浏览
看下这段代码,pygame写的一个循环播放背景音乐:
  1. #-*- coding: utf-8 -*-
  2. #file:test.py
  3. #
  4. import threading
  5. import pygame

  6. pygame.mixer.init()
  7. class player(threading.Thread):
  8.     def __init__(self,song_path,end_flag):
  9.         threading.Thread.__init__(self)
  10.         self.end_flag = end_flag
  11.         self.song_path = song_path
  12.     def run(self):
  13.         pygame.mixer.music.load(self.song_path)
  14.         pygame.mixer.music.play()
  15.         while pygame.mixer.music.get_busy():
  16.               continue
  17.         self.end_flag.remove('play')
  18.         self.end_flag.append('done')

  19. class listen(threading.Thread):
  20.     def __init__(self,song_path,end_flag):
  21.         threading.Thread.__init__(self)
  22.         self.end_flag = end_flag
  23.         self.song_path = song_path
  24.     def run(self):
  25.         while True:
  26.             if self.end_flag[0] == 'done':
  27.                self.end_flag.remove('done')
  28.                self.end_flag.append('play')
  29.                p = player(self.song_path,self.end_flag)
  30.                p.setDaemon(True)
  31.                p.start()
  32.                while True:
  33.                     if p.isAlive():
  34.                         break
  35.                     else:
  36.                         p.start()
  37. end_flag=['play']
  38. song_path='/host/KuGou/任贤齐 - 风云决.mp3'         
  39. p=player(song_path,end_flag)
  40. l=listen(song_path,end_flag)
  41. p.start()
  42. l.start()

复制代码
这样单独的测试没问题,可以循环播放歌曲.可当我在我的窗口模块使用,则不能循环播放了,求解答.

论坛徽章:
0
2 [报告]
发表于 2012-06-18 10:46 |只看该作者
本帖最后由 anonymous0502 于 2012-06-18 10:46 编辑

貌似还不错,我把别人写的两个例子合起来了。

代码分别来自:
http://www.willmcgugan.com/blog/ ... -pixel-with-pygame/
http://www.python-forum.org/pyth ... php?t=10631&f=2


subpixel.rar

190.59 KB, 下载次数: 5

论坛徽章:
0
3 [报告]
发表于 2012-06-18 10:53 |只看该作者
pygame.mixer.music.play(-1,0)就可以循环了,主程序里起一个线程运行你的线程类或函数就可以了。不知道你为什么要用两个线程。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP