sound_player.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2015-2019 Autoware Foundation
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import os
  17. import sys
  18. import rospy
  19. import yaml
  20. import subprocess
  21. from std_msgs.msg import String
  22. str_fn_dic = {}
  23. def load_yaml(filename, def_ret=None):
  24. dir = os.path.abspath(os.path.dirname(__file__)) + "/"
  25. path = dir + filename
  26. if not os.path.isfile(path):
  27. return def_ret
  28. print('loading ' + filename)
  29. f = open(dir + filename, 'r')
  30. d = yaml.load(f)
  31. f.close()
  32. return d
  33. def node_is_exist(node_name):
  34. subprocess.call([ 'sh', '-c', 'echo y | rosnode cleanup' ])
  35. run_nodes = subprocess.check_output([ 'rosnode', 'list' ]).strip().split('\n')
  36. return node_name in run_nodes
  37. def callback(data):
  38. fn = str_fn_dic.get(data.data)
  39. if fn is None:
  40. print('Invalid msg str "' + data.data +'"')
  41. return
  42. subprocess.call(['rosrun', 'sound_play', 'play.py', fn] )
  43. def sound_player():
  44. proc = None
  45. if node_is_exist('/sound_play'):
  46. print('already, sound_play exist.')
  47. else:
  48. proc = subprocess.Popen(['rosrun', 'sound_play', 'soundplay_node.py'])
  49. pack_path = subprocess.check_output([ 'rospack', 'find', 'sound_player' ]).strip()
  50. global str_fn_dic
  51. str_fn_dic = load_yaml('sound_player.yaml', {})
  52. for (k,fn) in str_fn_dic.items():
  53. fn = os.path.expandvars(os.path.expanduser(fn))
  54. if not os.path.isabs(fn):
  55. if '/' in fn:
  56. fn = pack_path + '/' + fn
  57. else:
  58. cmd = 'find ' + pack_path + '/wavs' + ' -name ' + fn
  59. fn = subprocess.check_output([ 'sh', '-c', cmd ]).strip().split('\n')[0]
  60. str_fn_dic[k] = fn
  61. rospy.init_node('sound_player', anonymous=True)
  62. rospy.Subscriber('sound_player', String, callback);
  63. rospy.spin()
  64. if proc:
  65. proc.terminate()
  66. if __name__ == '__main__':
  67. sound_player()
  68. # EOF